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

后端 未结 1 1255
你的背包
你的背包 2021-01-05 03:47

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.

1条回答
  •  悲&欢浪女
    2021-01-05 04:24

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

    
    

    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 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)
    

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题