Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

HtmlHelper for enums in ASP.NET MVC3

, 6 Apr 2011 LGPL3
Rate this:
Please Sign up or sign in to vote.
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.

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:

@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:

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

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Share

About the Author

jgauffin
Founder Gauffin Interactive AB
Sweden Sweden
Founder of OneTrueError, a .NET service which captures, analyzes and provide possible solutions for exceptions.
 
blog | twitter
Follow on   Twitter   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.141022.1 | Last Updated 6 Apr 2011
Article Copyright 2011 by jgauffin
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid