How to get the values of an enum into a SelectList

C#asp.net MvcEnums

C# Problem Overview


Imagine I have an enumeration such as this (just as an example):

public enum Direction{
    Horizontal = 0,
    Vertical = 1,
    Diagonal = 2
}

How can I write a routine to get these values into a System.Web.Mvc.SelectList, given that the contents of the enumeration are subject to change in future? I want to get each enumerations name as the option text, and its value as the value text, like this:

<select>
    <option value="0">Horizontal</option>
    <option value="1">Vertical</option>
    <option value="2">Diagonal</option>
</select>

This is the best I can come up with so far:

 public static SelectList GetDirectionSelectList()
 {
    Array values = Enum.GetValues(typeof(Direction));
    List<ListItem> items = new List<ListItem>(values.Length);

    foreach (var i in values)
    {
        items.Add(new ListItem
        {
            Text = Enum.GetName(typeof(Direction), i),
            Value = i.ToString()
        });
    }

    return new SelectList(items);
 }

However this always renders the option text as 'System.Web.Mvc.ListItem'. Debugging through this also shows me that Enum.GetValues() is returning 'Horizontal, Vertical' etc. instead of 0, 1 as I would've expected, which makes me wonder what the difference is between Enum.GetName() and Enum.GetValue().

C# Solutions


Solution 1 - C#

It's been awhile since I've had to do this, but I think this should work.

var directions = from Direction d in Enum.GetValues(typeof(Direction))
           select new { ID = (int)d, Name = d.ToString() };
return new SelectList(directions , "ID", "Name", someSelectedValue);

Solution 2 - C#

There is a new feature in ASP.NET MVC 5.1 for this.

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum

@Html.EnumDropDownListFor(model => model.Direction)

Solution 3 - C#

This is what I have just made and personally I think its sexy:

 public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
        {
            return (Enum.GetValues(typeof(T)).Cast<T>().Select(
                enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
        }

I am going to do some translation stuff eventually so the Value = enu.ToString() will do a call out to something somewhere.

Solution 4 - C#

To get the value of an enum you need to cast the enum to its underlying type:

Value = ((int)i).ToString();

Solution 5 - C#

I wanted to do something very similar to Dann's solution, but I needed the Value to be an int and the text to be the string representation of the Enum. This is what I came up with:

public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
    {
        return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = Enum.GetName(typeof(T), e), Value = e.ToString() })).ToList();
    }

Solution 6 - C#

In ASP.NET Core MVC this is done with tag helpers.

<select asp-items="Html.GetEnumSelectList<Direction>()"></select>

Solution 7 - C#

maybe not an exact answer to the question, but in CRUD scenarios i usually implements something like this:

private void PopulateViewdata4Selectlists(ImportJob job)
{
   ViewData["Fetcher"] = from ImportFetcher d in Enum.GetValues(typeof(ImportFetcher))
                              select new SelectListItem
                              {
                                  Value = ((int)d).ToString(),
                                  Text = d.ToString(),
                                  Selected = job.Fetcher == d
                              };
}

PopulateViewdata4Selectlists is called before View("Create") and View("Edit"), then and in the View:

<%= Html.DropDownList("Fetcher") %>

and that's all..

Solution 8 - C#

Or:

foreach (string item in Enum.GetNames(typeof(MyEnum)))
{
    myDropDownList.Items.Add(new ListItem(item, ((int)((MyEnum)Enum.Parse(typeof(MyEnum), item))).ToString()));
}

Solution 9 - C#

return
            Enum
            .GetNames(typeof(ReceptionNumberType))
            .Where(i => (ReceptionNumberType)(Enum.Parse(typeof(ReceptionNumberType), i.ToString())) < ReceptionNumberType.MCI)
            .Select(i => new
            {
                description = i,
                value = (Enum.Parse(typeof(ReceptionNumberType), i.ToString()))
            });

Solution 10 - C#

    public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");

        var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
        //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() };

        return new SelectList(values, "ID", "Name", enumObj);
    }
    public static SelectList ToSelectList<TEnum>(this TEnum enumObj, string selectedValue) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");

        var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
        //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() };
        if (string.IsNullOrWhiteSpace(selectedValue))
        {
            return new SelectList(values, "ID", "Name", enumObj);
        }
        else
        {
            return new SelectList(values, "ID", "Name", selectedValue);
        }
    }

Solution 11 - C#

I have more classes and methods for various reasons:

Enum to collection of items

public static class EnumHelper
{
    public static List<ItemDto> EnumToCollection<T>()
    {
        return (Enum.GetValues(typeof(T)).Cast<int>().Select(
            e => new ItemViewModel
                     {
                         IntKey = e,
                         Value = Enum.GetName(typeof(T), e)
                     })).ToList();
    }
}

Creating selectlist in Controller

int selectedValue = 1; // resolved from anywhere
ViewBag.Currency = new SelectList(EnumHelper.EnumToCollection<Currency>(), "Key", "Value", selectedValue);

MyView.cshtml

@Html.DropDownListFor(x => x.Currency, null, htmlAttributes: new { @class = "form-control" })

Solution 12 - C#

I had many enum Selectlists and, after much hunting and sifting, found that making a generic helper worked best for me. It returns the index or descriptor as the Selectlist value, and the Description as the Selectlist text:

Enum:

public enum Your_Enum
{
    [Description("Description 1")]
    item_one,
    [Description("Description 2")]
    item_two
}

Helper:

public static class Selectlists
{
    public static SelectList EnumSelectlist<TEnum>(bool indexed = false) where TEnum : struct
    {
        return new SelectList(Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(item => new SelectListItem
        {
            Text = GetEnumDescription(item as Enum),
            Value = indexed ? Convert.ToInt32(item).ToString() : item.ToString()
        }).ToList(), "Value", "Text");
    }

    // NOTE: returns Descriptor if there is no Description
    private static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes != null && attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
}

Usage: Set parameter to 'true' for indices as value:

var descriptorsAsValue = Selectlists.EnumSelectlist<Your_Enum>();
var indicesAsValue = Selectlists.EnumSelectlist<Your_Enum>(true);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLee DView Question on Stackoverflow
Solution 1 - C#BrandonView Answer on Stackoverflow
Solution 2 - C#FredView Answer on Stackoverflow
Solution 3 - C#DanView Answer on Stackoverflow
Solution 4 - C#Andrew HareView Answer on Stackoverflow
Solution 5 - C#J.Noel.KView Answer on Stackoverflow
Solution 6 - C#FredView Answer on Stackoverflow
Solution 7 - C#Carl HörbergView Answer on Stackoverflow
Solution 8 - C#zkarolyiView Answer on Stackoverflow
Solution 9 - C#HamidView Answer on Stackoverflow
Solution 10 - C#Joao LemeView Answer on Stackoverflow
Solution 11 - C#Miroslav HolecView Answer on Stackoverflow
Solution 12 - C#RickLView Answer on Stackoverflow