How does one perform asp.net mvc 4 model binding for enums?

a 夏天 提交于 2019-11-30 03:51:39

问题


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.

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}

and the view model:

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?


回答1:


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
}

And in view

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


来源:https://stackoverflow.com/questions/11030052/how-does-one-perform-asp-net-mvc-4-model-binding-for-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!