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
Advertisement
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);
change the last line to
return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, enums);
thanks