Create MVC DropDownList from an Enum

C

Like many requested features, MVC 5 now has a built-in function to provide an Enum object and automatically build a dropdown list using the standard HtmlHelper. If you’re unfortunate and on an older version of MVC, here is an HtmlExtension that performs the same thing.

Using Html.EnumDropDownListFor with MVC 5 and above

If you are using MVC 5, you can simply use this: Html.EnumDropDownListFor(m => m.YourEnumObject) and you’re good to go.

Creating an HtmlHelper extension called EnumDropDownListFor

This solution is actually going to apply the same logic as a previous post I wrote Convert an Enum to a list and leveraging Enum.GetValues.

Here is the HtmlExtension method:

[code]
public static MvcHtmlString EnumDropDownListFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable values = Enum.GetValues(enumType).Cast();

IEnumerable items = from value in values
select new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};

// If the enum is nullable, add an ’empty’ item to the collection
if (metadata.IsNullableValueType)
items = SingleEmptyItem.Concat(items);

return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}
[/code]

This can be accessed the exact same with Html.EnumDropDownListFor(m => m.YourEnumObject).

About the author

By Jamie

My Books