MVC5:枚举单选按钮,标签为显示名称 [英] MVC5: Enum radio button with label as displayname

查看:26
本文介绍了MVC5:枚举单选按钮,标签为显示名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些枚举

public enum QuestionStart{[Display(Name="重复直到找到共同匹配")]重复直到找到共同点,[显示(名称=重复一次")]重复一次,[显示(名称=不重复")]不重复}公共枚举问题结束{[显示(名称=取消邀请")]取消邀请,[Display(Name="在第一个可用的共同日期与参与者一起计划")]FirstAvailableCommon,[Display(Name="在我第一个可用的共同日期与参与者一起计划")]你的第一个可用公共}

我有一个帮助类来显示枚举中每个字段的所有单选按钮

@model 枚举@foreach(Enum.GetValues(Model.GetType()) 中的 var 值){@Html.RadioButtonFor(m => m, value)@Html.Label(value.ToString())<br/>}

现在标签设置为值名称,而不是我为值提供的显示名称.

例如:

[Display(Name="取消邀请")]取消邀请

我得到了旁边带有 CancelInvitation 的单选按钮.

如何让它显示我给它的显示名称(Cancel Invitation)?

解决方案

解决方案来了 -

归功于这位非凡的绅士 - ThumNet,他为 Enum 编写了 RadioButtonList 作为扩展

第 1 步 -Views/Shared/EditorTemplates 目录(如果不存在,然后创建该目录) -

@model 枚举@{//在您的枚举上查找 [Display(Name="Some Name")] 或 [Display(Name="Some Name", ResourceType=typeof(ResourceFile)] 属性Func<枚举,字符串>getDescription = en =>{类型类型 = en.GetType();System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());if (memInfo != null && memInfo.Length > 0){object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute),错误的);if (attrs != null && attrs.Length > 0)返回 ((System.ComponentModel.DataAnnotations.DisplayAttribute)attrs[0]).GetName();}返回 en.ToString();};var listItems = Enum.GetValues(Model.GetType()).OfType().Select(e =>新的选择列表项(){文本 = getDescription(e),值 = e.ToString(),Selected = e.Equals(Model)});字符串前缀 = ViewData.TemplateInfo.HtmlFieldPrefix;整数索引 = 0;ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;foreach(listItems 中的 var li){string fieldName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);<div class="editor-radio">@Html.RadioButton(prefix, li.Value, li.Selected, new { @id = fieldName })@Html.Label(fieldName, li.Text)

}ViewData.TemplateInfo.HtmlFieldPrefix = 前缀;}

然后有你的枚举 -

公共枚举 QuestionEnd{[Display(Name = "取消邀请")]取消邀请,[Display(Name = "在第一个可用的共同日期与参与者一起计划")]FirstAvailableCommon,[Display(Name = "在我第一个可用的共同日期与参与者一起计划")]你的第一个可用公共}

第 2 步 - 创建模型 -

公共类 RadioEnumModel{公共问题结束 qEnd { 得到;放;}}

第 3 步 - 创建控制器操作 -

 public ActionResult Index(){RadioEnumModel m = new RadioEnumModel();返回视图(m);}

第 4 步 - 创建视图 -

@model MVC.Controllers.RadioEnumModel@Html.EditorFor(x => x.qEnd, "RadioButtonListEnum")

那么输出将是 -

I have these enums

public enum QuestionStart
{
    [Display(Name="Repeat till common match is found")]
    RepeatTillCommonIsFound,

    [Display(Name="Repeat once")]
    RepeatOnce,    

    [Display(Name="No repeat")]
    NoRepeat

}

public enum QuestionEnd
{
    [Display(Name="Cancel Invitation")]
    CancelInvitation,

    [Display(Name="Plan with participants on first available common date")]
    FirstAvailableCommon,

    [Display(Name="Plan with participants on my first available common date")]
    YourFirstAvailableCommon
}

and I have a helper class to show all the radiobutton for each field in enum

@model Enum
@foreach (var value in Enum.GetValues(Model.GetType()))
{
    @Html.RadioButtonFor(m => m, value)
    @Html.Label(value.ToString())
    <br/>
}

Right now the label is set to the value name and not the display name i have given for values.

For example for:

[Display(Name="Cancel Invitation")]
CancelInvitation

I get radio button with CancelInvitation next to it.

How can I make it display the Display name(Cancel Invitation) i have given to it?

解决方案

Here goes the solution -

Credit goes to this extraordinary gentleman - ThumNet, who wrote RadioButtonList for Enum as an extension

Step 1 - Create RadioButtonListEnum.cshtml file with below code (code from above reference) in Views/Shared/EditorTemplates directory (if not exist, then create that directory) -

@model Enum

@{
     // Looks for a [Display(Name="Some Name")] or a [Display(Name="Some Name", ResourceType=typeof(ResourceFile)] Attribute on your enum
    Func<Enum, string> getDescription = en =>
    {
        Type type = en.GetType();
        System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());

        if (memInfo != null && memInfo.Length > 0)
        {

            object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute),
                                                            false);

            if (attrs != null && attrs.Length > 0)
                return ((System.ComponentModel.DataAnnotations.DisplayAttribute)attrs[0]).GetName();
        }

        return en.ToString();
    };
    var listItems = Enum.GetValues(Model.GetType()).OfType<Enum>().Select(e =>
    new SelectListItem()
    {
        Text = getDescription(e),
        Value = e.ToString(),
        Selected = e.Equals(Model)
    });
    string prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
    int index = 0;
    ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;

    foreach (var li in listItems)
    {
        string fieldName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);
        <div class="editor-radio">
        @Html.RadioButton(prefix, li.Value, li.Selected, new { @id = fieldName }) 
        @Html.Label(fieldName, li.Text)    
        </div>
    }
    ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
}

Then have your enum -

public enum QuestionEnd
{
    [Display(Name = "Cancel Invitation")]
    CancelInvitation,

    [Display(Name = "Plan with participants on first available common date")]
    FirstAvailableCommon,

    [Display(Name = "Plan with participants on my first available common date")]
    YourFirstAvailableCommon
}

Step 2 - Create Model -

public class RadioEnumModel
{
    public QuestionEnd qEnd { get; set; }
}

Step 3 - Create Controller Action -

    public ActionResult Index()
    {
        RadioEnumModel m = new RadioEnumModel();
        return View(m);
    }

Step 4 - Create View -

@model MVC.Controllers.RadioEnumModel
@Html.EditorFor(x => x.qEnd, "RadioButtonListEnum")

Then the output would be -

这篇关于MVC5:枚举单选按钮,标签为显示名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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