如何对枚举执行asp.net MVC 4模型绑定? [英] How does one perform asp.net mvc 4 model binding for enums?

查看:57
本文介绍了如何对枚举执行asp.net MVC 4模型绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

asp.net mvc团队是否为枚举实现了默认模型绑定?一个现成的,不需要为枚举创建自定义模型绑定器.

Has the asp.net mvc team implemented a default model binding for enums? One that is out of the box and there is no need of creating a custom model binder for enums.

更新:
假设我有一个动作,该动作将接收视图模型,并且JSON对象将发布到该动作.

UPDATE:
Let's say I have an action that will be receiving a view model and a JSON object will be posted to the action.

jsObj{id:2, name:'mike', personType: 1}

和视图模型:

class ViewModel
{
    public int id {get;set;}
    public string name {get;set;}
    public PersonType personType{get;set;}
}

public enum PersonType : int
{
   Good = 1,
   Bad = 2,
   Evil = 3
}

人员类型会受到约束吗?

Will the person type be bound?

推荐答案

即使在较早的版本中也存在.此html和Gender = Male表单值正确绑定到Gender枚举属性.

It was there even with earlier versions. This html and Gender = Male form value is correctly binding to Gender enum property.

<select id="Gender" name="Gender">
     <option value="Male">Male</option>
     <option value="Female">Femal</option>
</select>

对于服务器端,我发现在视图模型中使用选择列表最简单

For the server side I find it easiest to use select lists in my view model

public class User
{
    public UserType UserType { get; set; }

    public IEnumerable<SelectListItem> UserTypesSelectList { get; set; }

    public User()
    {
        UserTypesSelectList = Enum.GetNames(typeof(UserType)).Select(name => new SelectListItem()
        {
            Text = name,
            Value = MakeEnumMoreUserFriendly(name)
        });
    }
}

public enum UserType
{
    First,
    Second
}

在视野中

@Html.DropDownListFor(model => model.UserType, Model.UserTypesSelectList)

这篇关于如何对枚举执行asp.net MVC 4模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆