Click here to Skip to main content
15,885,365 members
Articles / Web Development / HTML

HtmlHelper for enums in ASP.NET MVC3

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Apr 2011LGPL3 13.9K   2  
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, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Founder 1TCompany AB
Sweden Sweden

Comments and Discussions

 
-- There are no messages in this forum --