通用EditorTemplate与文本选择期权价值枚举 [英] Generic EditorTemplate for an Enum with Text Select Option Value

查看:147
本文介绍了通用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);
}

这篇关于通用EditorTemplate与文本选择期权价值枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆