How can I convert an enumeration into a List<SelectListItem>?

点点圈 提交于 2019-12-02 15:03:19
SLaks

You can use LINQ:

Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
    Text = v.ToString(),
    Value = ((int)v).ToString()
}).ToList();

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

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();
}

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

Now I used Tuple<string, string> but you can convert this to use anything:

var values = Enum.GetValues(typeof(DayOfWeek))
    .Cast<DayOfWeek>()
    .Select(d => Tuple.Create(((int)d).ToString(), d.ToString()))
    .ToList()

I used GetEnumSelectList from the Html Helper class

<select asp-for="MyProperty" class="form-control" asp-items="@Html.GetEnumSelectList<MyEnum>()" ></select>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!