In MVC 5, you can add a template to Views->Shared->EditorTemplates containing this code:
@model Enum
@{
var optionLabel = ViewData["optionLabel"] as string;
var htmlAttributes = ViewData["htmlAttributes"];
}
@Html.EnumDropDownListFor(m => m, optionLabel, htmlAttributes)
Example usage:
@Html.EditorFor(model => model.PropertyType,
new {
htmlAttributes = new { @class = "form-control" },
optionLabel = "Select"
})
In MVC 4, you don't have the EnumDropDownListFor
extension, but you could roll your own, which I did previously like this:
public static MvcHtmlString DropDownListFor<TModel, TEnum>
(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression,
string optionLabel = null, object htmlAttributes = null)
{
//This code is based on the blog - it's finding out if it nullable or not
Type metaDataModelType = ModelMetadata
.FromLambdaExpression(expression, htmlHelper.ViewData).ModelType;
Type enumType = Nullable.GetUnderlyingType(metaDataModelType) ?? metaDataModelType;
if (!enumType.IsEnum)
throw new ArgumentException("TEnum must be an enumerated type");
IEnumerable<SelectListItem> items = Enum.GetValues(enumType).Cast<TEnum>()
.Select(e => new SelectListItem
{
Text = e.GetDisplayName(),
Value = e.ToString(),
Selected = e.Equals(ModelMetadata
.FromLambdaExpression(expression, htmlHelper.ViewData).Model)
});
return htmlHelper.DropDownListFor(
expression,
items,
optionLabel,
htmlAttributes
);
}
References:
http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum
http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx