I\'m trying to use the Html.DropDownList
extension method but can\'t figure out how to use it with an enumeration.
Let\'s say I have an enumeration like
Here is a better encapsulated solution:
https://www.spicelogic.com/Blog/enum-dropdownlistfor-asp-net-mvc-5
Say here is your model:
Sample Usage:
Generated UI:
And generated HTML
The Helper Extension Source Code snap shot:
You can download the sample project from the link I provided.
EDIT: Here's the code:
public static class EnumEditorHtmlHelper
{
///
/// Creates the DropDown List (HTML Select Element) from LINQ
/// Expression where the expression returns an Enum type.
///
/// The type of the model.
/// The type of the property.
/// The HTML helper.
/// The expression.
///
public static MvcHtmlString DropDownListFor(this HtmlHelper htmlHelper,
Expression> expression)
where TModel : class
{
TProperty value = htmlHelper.ViewData.Model == null
? default(TProperty)
: expression.Compile()(htmlHelper.ViewData.Model);
string selected = value == null ? String.Empty : value.ToString();
return htmlHelper.DropDownListFor(expression, createSelectList(expression.ReturnType, selected));
}
///
/// Creates the select list.
///
/// Type of the enum.
/// The selected item.
///
private static IEnumerable createSelectList(Type enumType, string selectedItem)
{
return (from object item in Enum.GetValues(enumType)
let fi = enumType.GetField(item.ToString())
let attribute = fi.GetCustomAttributes(typeof (DescriptionAttribute), true).FirstOrDefault()
let title = attribute == null ? item.ToString() : ((DescriptionAttribute) attribute).Description
select new SelectListItem
{
Value = item.ToString(),
Text = title,
Selected = selectedItem == item.ToString()
}).ToList();
}
}