Creating a dropdown list from an enum in MVC and C#

by John Nye

16 Jan
2012

Recently I have been displaying enums as drop down lists on some MVC 3 projects and noticed there are a few people out there looking for a solution

Here is an enum helper I use that turns an enum into a select list. Note: If the enum has a description (using the DescriptionAttribute) it will use that as its display text

public static class EnumHelper
{
    // Get the value of the description attribute if the   
    // enum has one, otherwise use the value.  
    public static string GetDescription<TEnum>(this TEnum value)
    {
        var fi = value.GetType().GetField(value.ToString());

        if (fi != null)
        {
            var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }

        return value.ToString();
    }

    /// <summary>
    /// Build a select list for an enum
    /// </summary>
    public static SelectList SelectListFor<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null
                         : new SelectList(BuildSelectListItems(t), "Value", "Text");
    }

    /// <summary>
    /// Build a select list for an enum with a particular value selected 
    /// </summary>
    public static SelectList SelectListFor<T>(T selected) where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null
                         : new SelectList(BuildSelectListItems(t), "Value", "Text", selected.ToString());
    }

    private static IEnumerable<SelectListItem> BuildSelectListItems(Type t)
    {
        return Enum.GetValues(t)
                   .Cast<Enum>()
                   .Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() });
    }
}

Once you have this helper class in place you can do the following.

In your controller:

//If you don't have an enum value use the type
ViewBag.DropDownList = EnumHelper.SelectListFor<MyEnum>();

//If you do have an enum value use the value (the value will be marked as selected)    
ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);

In your View:

@Html.DropDownList("DropDownList")
@* OR *@
@Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null)

Hey presto you have a drop down list for your enums which binds back to your view model on post.

Comments 11

Moxos says: 3786 days ago

You're a lifesaver. So many redicilously complicated solutions out there. ViewBag certainly has it's drawbacks but this has gotten me back on track again.

John says: 3786 days ago

Hey @Moxos, glad to help. Thanks for commenting, you are the first person to comment since launching my custom comment system. Hoorar!

Iman Namvar says: 3777 days ago

in this line i have an error , please hep me !

return attributes[0].Description;

compiler cannot handle "Description" !   
Iman Namvar says: 3777 days ago

oops!
i add using System.ComponentModel; and problem solved :)

John says: 3776 days ago

Hi Iman,

Glad you solved it, I'll add a note to include the using statement for future reference

Alex says: 3604 days ago

Nice, thanks John, you saved my fingers some typing.

John says: 3600 days ago

Hi Alex,

No problem at all. Glad to help.

Rashedul says: 2987 days ago

Greate job

Ankush Mehndiratta says: 1739 days ago

awesome sir

scott says: 628 days ago

//If you do have an enum value use the value (the value will be marked as selected)
ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);

selected not working

scott says: 544 days ago

how can i get the SelectListItem value =numeric, not ToString()?

Leave a message...

18 Apr
2024