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

Viewed 50956

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 enum is associated with. Is there any elegant way of doing this conversion?

8 Answers

I used GetEnumSelectList from the Html Helper class

<select asp-for="MyProperty" class="form-control" asp-items="@Html.GetEnumSelectList<MyEnum>()" ></select>

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.

In the Asp.Net Core, just use:

<select asp-for="MyEnum" asp-items="Html.GetEnumSelectList(typeof(MyEnum))"></select>

Or

Create Helper

public static class EnumHelper
{
    public static IEnumerable<SelectListItem> GetEnumSelectList<TEnum>(bool isNullable = false)
        where TEnum : struct
    {
        IList<SelectListItem> selectLists = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(c => new SelectListItem()
        {
            Text = GetDisplayName(c),
            Value = c.ToString()
        }).ToList();

        if (isNullable)
        {
            selectLists.Add(new SelectListItem());
        }

        return selectLists.OrderBy(c => c.Value);
    }

    public static string GetDisplayName<TEnum>(TEnum enumVal)
    {
        DisplayAttribute attr = GetAttribute<DisplayAttribute>(enumVal);

        if (attr != null)
        {
            return attr.Name;
        }

        return enumVal?.ToString() ?? string.Empty;
    }

    public static TEnum GetAttribute<TEnum>(object enumVal) where TEnum : Attribute
    {
        if (enumVal == null)
        {
            return default;
        }

        Type type = enumVal.GetType();
        MemberInfo[] memInfo = type.GetMember(enumVal.ToString());

        if (memInfo.Length == 0)
        {
            return null;
        }

        object[] attributes = memInfo[0].GetCustomAttributes(typeof(TEnum), false);
        return attributes.Length > 0 ? (TEnum)attributes[0] : null;
    }
}

To use

@using MyClass.Helpers;
    
<select asp-for="MyEnum" asp-items="EnumHelper.GetEnumSelectList<MyEnum>(true)">/select>
Related