通用EditorTemplate与文本选择期权价值枚举

问题描述:

我一直用这个编辑器模板枚举:

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>

该EnumDropDownListFor()给了我这样的:

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.

下面是一个扩展方法应该有所帮助:

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