【问题标题】:Generic EditorTemplate for an Enum with Text Select Option Value具有文本选择选项值的枚举的通用 EditorTemplate
【发布时间】:2015-07-15 21:13:50
【问题描述】:

我一直在使用这个编辑器模板进行枚举:

@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() 给了我这样的东西:

<option value="0">blah0</option>
<option value="1">blah1</option>

我想创建一个对值和文本都使用枚举文本(或显示名称)的版本。

<option value="blah0">blah0</option>
<option value="blah1">blah1</option>

我找到了一种方法来使用键入到特定枚举的模板,但如果可能的话,我想对所有枚举进行通用操作。

【问题讨论】:

    标签: asp.net-mvc enums mvc-editor-templates


    【解决方案1】:

    这是一个应该有帮助的扩展方法:

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

    【讨论】:

    • 感谢 Rob,这正是我一直在寻找的东西,非常感谢。
    • 我在第一行收到此错误“提供的类型必须是枚举。参数名称:enumType”。知道为什么吗?我正在谷歌上搜索,但运气不佳。
    • 是的。 Enum 本身不算作枚举。我认为 @model 是一个枚举,因为您想要最大的灵活性。有办法解决这个问题。编辑待定。
    • 已编辑。您必须将@Model.GetType() 添加到您的通话中,但应该这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2017-06-19
    • 2023-04-04
    • 2010-12-27
    • 1970-01-01
    相关资源
    最近更新 更多