问题
I have been using this editor template for enums:
@model Enum
@{
var htmlAttributesFromView = ViewData["htmlAttributes"] ?? new { };
var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesFromView, new { @class = "form-control" });
}
<div class="form-group">
@Html.LabelFor(model => model, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-8">
@Html.EnumDropDownListFor(x => x, htmlAttributes)
@Html.ValidationMessageFor(model => model)
</div>
<a class="infoonclick col-md-1" title="@Html.DisplayNameFor(model => model)" data-content="@Html.DescriptionFor(model => model)">
<span class="fa fa-info-circle"></span>
</a>
</div>
The EnumDropDownListFor() gives me something like this:
<option value="0">blah0</option>
<option value="1">blah1</option>
I would like to create a version that uses the enum text (or display name) for both value and text.
<option value="blah0">blah0</option>
<option value="blah1">blah1</option>
I've found a way to do it with a template typed to a specific enum, but if possible I'd like to do it generically for all enums.
回答1:
Here's an extension method that should help:
public static MvcHtmlString EnumTextDropDownListFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, Enum>> expression, Type enumType, object htmlAttributes)
{
var enumValues = Enum.GetValues(enumType).OfType<Enum>().Select(v => v.ToString()).ToArray();
var selectList = new SelectList(enumValues.Select(v => new SelectListItem { Text = v, Value = v }));
return html.DropDownListFor(expression, selectList, htmlAttributes);
}
来源:https://stackoverflow.com/questions/31441236/generic-editortemplate-for-an-enum-with-text-select-option-value