How do I populate a dropdownlist with enum values?

I’m using a helper that i found here to populate my SelectLists with a generic enum type, i did a little modification to add the selected value though, here’s how it looks like :

public static SelectList ToSelectList<T>(this T enumeration, string selected)
{
    var source = Enum.GetValues(typeof(T));

    var items = new Dictionary<object, string>();

    var displayAttributeType = typeof(DisplayAttribute);

    foreach (var value in source)
    {
        FieldInfo field = value.GetType().GetField(value.ToString());

        DisplayAttribute attrs = (DisplayAttribute)field.
                      GetCustomAttributes(displayAttributeType, false).FirstOrDefault()

        items.Add(value, attrs != null ? attrs.GetName() : value.ToString());
    }

    return new SelectList(items, "Key", "Value", selected);
}

The nice thing about it is that it reads the DisplayAttribute as the title rather than the enum name. (if your enums contain spaces or you need localization then it makes your life much easier)

So you will need to add the Display attirubete to your enums like this :

public enum User_Status
{
    [Display(Name = "Waiting Activation")]
    Pending,    // User Account Is Pending. Can Login / Can't participate

    [Display(Name = "Activated" )]
    Active,                // User Account Is Active. Can Logon

    [Display(Name = "Disabled" )]
    Disabled,          // User Account Is Diabled. Can't Login
}

and this is how you use them in your views.

<%: Html.DropDownList("ChangeStatus" , ListExtensions.ToSelectList(Model.statusType, user.Status))%>

Model.statusType is just an enum object of type User_Status.

That’s it , no more SelectLists in your ViewModels. In my example I’m refrencing an enum in my ViewModel but you can Refrence the enum type directly in your view though. I’m just doing it to make everything clean and nice.

Hope that was helpful.

Leave a Comment