How can I convert an enumeration into a List?

后端 未结 7 1163
难免孤独
难免孤独 2021-01-30 10:31

i have an asp.net-mvc webpage and i want to show a dropdown list that is based off an enum. I want to show the text of each enum item and the id being the int value that the en

7条回答
  •  一向
    一向 (楼主)
    2021-01-30 10:44

    Since MVC 5.1, the most elegant way would be to use EnumDropDownListFor method of Html helper if you need to populate select options in your view:

    @Html.EnumDropDownListFor(m => m.MyEnumProperty,new { @class="form-control"})
    

    or GetSelectList method of EnumHelper in your controller:

    var enumList = EnumHelper.GetSelectList(typeof (MyEnum));
    

提交回复
热议问题