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

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).

Published on Feb 2, 2020

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

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.