Generic EditorTemplate for an Enum with Text Select Option Value

心已入冬 提交于 2020-02-04 07:31:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!