How do you create a dropdownlist from an enum in ASP.NET MVC?

后端 未结 30 1920
不知归路
不知归路 2020-11-21 16:36

I\'m trying to use the Html.DropDownList extension method but can\'t figure out how to use it with an enumeration.

Let\'s say I have an enumeration like

30条回答
  •  失恋的感觉
    2020-11-21 16:43

    I would like to answer this question in a different way where, user need not to do anything in controller or Linq expression. This way...

    I have a ENUM

    public enum AccessLevelEnum
        {
            /// 
            /// The user cannot access
            /// 
            [EnumMember, Description("No Access")]
            NoAccess = 0x0,
    
            /// 
            /// The user can read the entire record in question
            /// 
            [EnumMember, Description("Read Only")]
            ReadOnly = 0x01,
    
            /// 
            /// The user can read or write
            /// 
            [EnumMember, Description("Read / Modify")]
            ReadModify = 0x02,
    
            /// 
            /// User can create new records, modify and read existing ones
            /// 
            [EnumMember, Description("Create / Read / Modify")]
            CreateReadModify = 0x04,
    
            /// 
            /// User can read, write, or delete
            /// 
            [EnumMember, Description("Create / Read / Modify / Delete")]
            CreateReadModifyDelete = 0x08,
    
            /*/// 
            /// User can read, write, or delete
            /// 
            [EnumMember, Description("Create / Read / Modify / Delete / Verify / Edit Capture Value")]
            CreateReadModifyDeleteVerify = 0x16*/
        }
    

    Now I canto simply create a dropdown by using this enum.

    @Html.DropDownList("accessLevel",new SelectList(AccessLevelEnum.GetValues(typeof(AccessLevelEnum))),new { @class = "form-control" })
    

    OR

    @Html.DropDownListFor(m=>m.accessLevel,new SelectList(AccessLevelEnum.GetValues(typeof(AccessLevelEnum))),new { @class = "form-control" })
    

    If you want to make a index selected then try this

    @Html.DropDownListFor(m=>m.accessLevel,new SelectList(AccessLevelEnum.GetValues(typeof(AccessLevelEnum)) , AccessLevelEnum.NoAccess ),new { @class = "form-control" })
    

    Here I have used AccessLevelEnum.NoAccess as an extra parameter for default selecting the dropdown.

提交回复
热议问题