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 8

Moxos says: 1443 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: 1443 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: 1434 days ago

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

return attributes[0].Description;

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

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

John says: 1433 days ago

Hi Iman,

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

Alex says: 1262 days ago

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

John says: 1257 days ago

Hi Alex,

No problem at all. Glad to help.

Rashedul says: 644 days ago

Greate job

Leave a message...

18 Nov
2017