I had the same problem and created these extension methods:
using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Web.Mvc; using System.Web.Mvc.Html; public static class EnumHelper { private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = string.Empty, Value = string.Empty } }; public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression) { return htmlHelper.EnumDropDownListFor(expression, null); } public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes) { var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); var enumType = GetNonNullableModelType(metadata); var values = Enum.GetValues(enumType).Cast<TEnum>(); var items = values.Select(value => new SelectListItem { Text = GetName(value), Value = value.ToString(), Selected = value.Equals(metadata.Model) }); if (metadata.IsNullableValueType) { items = SingleEmptyItem.Concat(items); } return htmlHelper.DropDownListFor(expression, items, htmlAttributes); } private static string GetName<TEnum>(TEnum value) { var displayAttribute = GetDisplayAttribute(value); return displayAttribute == null ? value.ToString() : displayAttribute.GetName(); } private static DisplayAttribute GetDisplayAttribute<TEnum>(TEnum value) { return value.GetType() .GetField(value.ToString()) .GetCustomAttributes(typeof(DisplayAttribute), false) .Cast<DisplayAttribute>() .FirstOrDefault(); } private static Type GetNonNullableModelType(ModelMetadata modelMetadata) { var realModelType = modelMetadata.ModelType; var underlyingType = Nullable.GetUnderlyingType(realModelType); return underlyingType ?? realModelType; } }
You can use these extension methods in your views as follows:
@Html.EnumDropDownListFor(c=> comment.CommentType)
You should now see a drop-down list containing the names of the enumeration values ββaccording to their DisplayAttribute .
The actual retrieval of the displayed enumeration value is performed in the GetName method, which first uses the GetDisplayAttribute method to try to retrieve the DisplayAttribute enumeration value. If the enum value was really embellished with DisplayAttribute , it will use this to get the display name. If there is no DisplayAttribute , we simply return the name of the enumeration value.
source share