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

8

70

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?

Alanson answered 15/8, 2010 at 21:59 Comment(1)
the answer by Maksim Vi. should really be the correct answer.Beamends
E
148

You can use LINQ:

Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
    Text = v.ToString(),
    Value = ((int)v).ToString()
}).ToList();
Endanger answered 15/8, 2010 at 22:5 Comment(5)
Although LINQ has become the unofficial name of the Enumerable Extensions I can't help but wonder if something more appropriate exists.Hipbone
It's part of the Linq namespace and project, and IMO the correct name. Linq is just also the name for the language extension.Theologue
this code above is not compiling. i am trying to do this: List<SelectListItem> dropdown = Enum.GetValues(typeof(EventType)).Select(v => new SelectListItem { Selected = (int)v == id, Text = v.ToString(), Value = ((int)v).ToString() }).ToList(); return dropdown; but getting an error: "Cannot cast expression from TSource to int" in the lines that are doing (int)v)Alanson
You could say: "You can use System.Linq"Hebdomadal
@Endanger nice point but it does not take into account Order in Display attributeHeavyset
N
39

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));
Narton answered 15/7, 2015 at 19:42 Comment(4)
Very slick! Did not know about this... should be the correct answer.Beamends
wow, I didn't know. a lot of code lines saved for now on! Thank you man!Shears
For those wondering about the EnumHelper, do something like this: Html.DropDownList("SearchEnum", EnumHelper.GetSelectList(typeof(MyEnum)))Regurgitation
I love this answer. I totally forgot about EnumDropDownListFor.. What happens if you use IEnumerable<Enum> ?Adamok
S
8

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();
}
Seasoning answered 3/12, 2015 at 12:27 Comment(0)
R
7

I used GetEnumSelectList from the Html Helper class

<select asp-for="MyProperty" class="form-control" asp-items="@Html.GetEnumSelectList<MyEnum>()" ></select>
Rysler answered 19/10, 2017 at 12:47 Comment(0)
H
4

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()
Hipbone answered 15/8, 2010 at 22:4 Comment(0)
B
4

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

Bridgework answered 15/8, 2010 at 22:5 Comment(0)
W
0

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.

Withdrew answered 29/12, 2019 at 14:35 Comment(0)
T
0

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>
Topfull answered 20/5, 2021 at 2:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.