Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

HtmlHelper for enums in ASP.NET MVC3

0.00/5 (No votes)
6 Apr 2011 1  
How to get enums to work with HtmlHelpers.

Have you tried to get enums working with HtmlHelpers? It can be a hassle and here is my solution for it. It requires that you tag each entry in the enum with a [Description] attribute.

C#
public static class SelectExtensions
{
    public static string GetInputName<TModel, TProperty>(
           Expression<Func<TModel, TProperty>> expression)
    {
        if (expression.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression methodCallExpression = 
                 (MethodCallExpression)expression.Body;
            string name = GetInputName(methodCallExpression);
            return name.Substring(expression.Parameters[0].Name.Length + 1);

        }
        return expression.Body.ToString().Substring(
               expression.Parameters[0].Name.Length + 1);
    }

    private static string GetInputName(MethodCallExpression expression)
    {
        // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw...
        MethodCallExpression methodCallExpression = 
                  expression.Object as MethodCallExpression;
        if (methodCallExpression != null)
        {
            return GetInputName(methodCallExpression);
        }
        return expression.Object.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
           this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, 
           TProperty>> expression) where TModel : class
    {
        string inputName = GetInputName(expression);
        var value = htmlHelper.ViewData.Model == null
            ? default(TProperty)
            : expression.Compile()(htmlHelper.ViewData.Model);

        return htmlHelper.DropDownList(inputName, 
               ToSelectList(typeof(TProperty), value.ToString()));
    }

    public static SelectList ToSelectList(Type enumType, string selectedItem)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var item in Enum.GetValues(enumType))
        {
            FieldInfo fi = enumType.GetField(item.ToString());
            var attribute = fi.GetCustomAttributes(typeof(
                               DescriptionAttribute), true).FirstOrDefault();
            var title = attribute == null ? item.ToString() : 
                       ((DescriptionAttribute)attribute).Description;
            var listItem = new SelectListItem
                {
                    Value = ((int)item).ToString(),
                    Text = title,
                    Selected = selectedItem == ((int)item).ToString()
                };
            items.Add(listItem);
        }

        return new SelectList(items, "Value", "Text");
    }
}

Usage:

C#
@Html.EnumDropDownListFor(m => m.SubscriptionMode);

If you want to be able to use it for validation, you need to be able to have an “undefined” entry in your enum and do the following change:

C#
// replace "Value = ((int)item).ToString()," in to select list.
Value = (int)item == 0 ? string.Empty : ((int)item).ToString(),

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here