Turning an enum into a DropDownList in ASP.Net MVC

Jul 13, 2013 • val antonini

Thanks to this post.

A quick code stub to convert an enum into an MVC drop down list. You can decorate an enum value with a description to have it display that instead of the enum text.

using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Extensions
{
    public static class HtmlDropDownExtensions
    {
        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes = null)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            var enumItems = Enum.GetValues(typeof (TEnum)).Cast<Enum>();

            var items = enumItems.Select(item => new SelectListItem()
            {
                Value = item.ToString(),
                Text = GetDescriptionFromEnum(item),
                Selected = item.Equals(metadata.Model)
            }).ToList();

            return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
        }

        public static string GetDescriptionFromEnum(Enum e)
        {
            var field = e.GetType().GetField(e.ToString());

            if (field == null) return e.ToString();

            var description = field.GetCustomAttributes(typeof (DescriptionAttribute), false)
                .Cast<DescriptionAttribute>()
                .FirstOrDefault();

            return description == null ? e.ToString() : description.Description;
        }
    }
}
Usage:
@Html.EnumDropDownListFor(m => m.Position)