asp.net的MVC 4模型绑定的枚举 [英] asp.net mvc 4 model binding for enums

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

问题描述

的asp.net mvc的团队实现了一个默认的模式,枚举绑定?所以,它是开箱和没有必要创建自定义模型粘合剂枚举

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

更新:
可以说,我有一个将收到一个视图模型的动作。和一个JSON对象将被张贴到行动。

UPDATE:
Lets 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 binded?

推荐答案

在那里甚至更早的版本。这html和性别=男形式值是否正确绑定到性别枚举属性。

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天全站免登陆