ASP.NET MVC 2 DropDownlist Extensions for Enum

The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view. The DropDownList helper renders a drop-down list.

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


But the problem is MVC framework doesn’t provide any Helper method to work with Enum Type. So we need to extend Html Helper to work with Enum.

public enum UserType
{
    Admin=1,
    PM= 2,
    Developer = 3
}

public static MvcHtmlString DropDownList(this HtmlHelper helper, string name, Type type)
{
    if (!type.IsEnum) throw new ArgumentException("Type is not an enum.");
    var enums = new List<SelectListItem>();
    foreach (int value in Enum.GetValues(type))
    {
         enums.Add(new SelectListItem { Value = value.ToString(), Text = Enum.GetName(type, value) });
    }
     return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, enums);
}

For Strongly Typed

public static MvcHtmlString DropDownListFor(this HtmlHelper htmlHelper, Expression<Func> expression, 
            Type type, object htmlAttributes)
{
     if (!type.IsEnum) throw new ArgumentException("Type is not an enum.");
     var enums = new List<SelectListItem>();
     foreach (int value in Enum.GetValues(type))
     {
         enums.Add(new SelectListItem { Value = value.ToString(), Text = Enum.GetName(type, value) });
     }
     return System.Web.Mvc.Html.SelectExtensions.DropDownListFor(htmlHelper, expression, 
         enums, htmlAttributes);

}

Now let’s use those methods on view.

<%= Html.DropDownList("UserType", typeof(UserType)) %> 
<%= Html.DropDownListFor(model=>model.UserType, typeof(UserType), null) %>  //for strongly typed
Advertisements

2 thoughts on “ASP.NET MVC 2 DropDownlist Extensions for Enum

  1. Thank you, that was helpfull. Only one thing: I don’t know if I am doing something wrong, but I only got it to work changing the last line of the code from

    return Html.SelectExtensions.DropDownList(helper, name, enums);

    to

    return helper.DropDownList(name, enums);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s