How can I convert an enumeration into a List?

后端 未结 7 1159
难免孤独
难免孤独 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:36

    You can use Enum.GetNames() to get a string array containing the names of the enum items. If your item names are user friendly, then this is probably good enough. Otherwise, you could create your own GetName() method that would return a nice name for each item.

    OR - if the enum will never (or rarely) change, you could just create a method that directly adds hard-coded items to your dropdown. This is probably more efficient (if that is important to you).

    0 讨论(0)
  • 2021-01-30 10:40

    It's super easy with my extension method. Which also allows you to provide options like adding placeholder, grouping and disabling certain values or groups. Give it a try.

    enum Color
    {       
        Blue,
        [Category("Light")]
        [DisplayName("Light Blue")]
        LBlue,
        [Category("Dark")]
        [DisplayName("Dark Blue")]
        DBlue,
        Red,
        [Category("Dark")]
        [DisplayName("Dark Red")]
        DRed,
        [Category("Light")]
        [DisplayName("Light Red")]
        LRed,
        Green,
        [Category("Dark")]
        [DisplayName("Dark Green")]
        DGreen,
        [Category("Light")]
        [DisplayName("Light Green")]
        LGreen  
    }
    
    var list = typeof(Color).ToSelectList();
    
    //or with custom options
    var list = typeof(Color).ToSelectList(new SelectListOptions { Placeholder = "Please Select A Color"});
    

    Here's the link to the github repo.

    0 讨论(0)
  • 2021-01-30 10:43

    You can use LINQ:

    Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
        Text = v.ToString(),
        Value = ((int)v).ToString()
    }).ToList();
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2021-01-30 10:47

    I used GetEnumSelectList from the Html Helper class

    <select asp-for="MyProperty" class="form-control" asp-items="@Html.GetEnumSelectList<MyEnum>()" ></select>
    
    0 讨论(0)
  • 2021-01-30 10:56

    I did this using a static method that I could reuse.

    public static IEnumerable<SelectListItem> EnumToSelectList<T>()
    {
        return (Enum.GetValues(typeof(T)).Cast<T>().Select(
            e => new SelectListItem() { Text = e.ToString(), Value = e.ToString() })).ToList();
    }
    
    0 讨论(0)
提交回复
热议问题