Follow @endyourif rss Facebook LinkedIn

Create MVC DropDownList from an Enum Create MVC DropDownList from an Enum

Published on Feb 2, 2020

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:


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);
}


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

Tags: ASP.NET MVC and Web API Tutorial | enum | dropdownlistfor

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP