Creating a drop down list from an enum in ASP.NET MVC

I recently had to create a drop-down list from an enumeration in an MVC site.  Having seen a number of posts on forums asking the best way of doing this, I thought I would post my solution here.

Step 1: Create an extension method for enums which converts them into a SelectList

    public static class EnumExtensions
   {
        public static SelectList ToSelectList<TEnum>(this TEnum enumObject)
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                         select new { ID = e, Name = e.ToString() };


            return new SelectList(values, "Id", "Name", enumObject);
        }
    }


Step 2. Use the Html helper for the drop down list

<%: Html.DropDownList("State", Model.State.ToSelectList()) %>

NB1.  In this example I have a property called State on my object and my view is strongly typed.
NB2.  Don't forget to include the 'imports' statement for the namespace your extension method resides in.

Comments