【问题标题】:MVC5: Enum radio button with label as displaynameMVC5:带有标签的枚举单选按钮作为显示名称
【发布时间】:2014-03-07 21:42:58
【问题描述】:

我有这些枚举

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
}

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

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

现在标签设置为值名称,而不是我为值指定的显示名称。

例如:

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

我得到带有CancelInvitation 的单选按钮。

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

【问题讨论】:

  • @Biploav13,试试这个解决方案,让我知道结果 - stackoverflow.com/questions/9328972/…
  • 代码是否适用于 MVC5 ?
  • 我应该在哪里实现该功能?我的视图使用 Html.EditorFor 并且我有帮助类来显示单选按钮。
  • 我将标签更改为更特定于版本:MVC4 似乎无法很好地处理将 dynamic 提供给 RadioButtonFor 的问题
  • 我想我更新到 mvc 5.1 但我该如何检查?

标签: c# asp.net-mvc enums asp.net-mvc-5


【解决方案1】:

我发现其中一些答案令人困惑,这就是我最终获得结果的方式。希望这对其他人有帮助。

将其放入扩展方法文件中:

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr =
                   Attribute.GetCustomAttribute(field,
                     typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }
    return null;
}

确保将与枚举类型相同的属性添加到实际模型中,以便绑定单选按钮选择。

为您的特定枚举创建一个编辑器模板。然后在您的视图中像这样引用它:

@Html.EditorFor(m => m.MyEnumTypePropertyName)

然后将以下内容添加到您的 EditorTemplate:

@using MyProject.ExtensionMethods;
@model MyProject.Models.Enums.MyEnumType

    @foreach (MyEnumType value in Enum.GetValues(typeof(MyEnumType)))
    {
        <div>
            @Html.Label(value.GetDescription())
            @Html.RadioButtonFor(m => m, value)
        </div>
    }

记住 - 如果您出于某种原因没有选择单选按钮,则发布时枚举属性的默认值将始终是包中的第一个(即零),而不是 null。

【讨论】:

    【解决方案2】:

    这是一个解决方案,它使用扩展方法和编辑器模板从 display 属性创建具有本地化名称的单选组。

    扩展方法

    public static string DisplayName(this Enum enumValue)
    {
        var enumType = enumValue.GetType();
        var memberInfo = enumType.GetMember(enumValue.ToString()).First();
    
        if (memberInfo == null || !memberInfo.CustomAttributes.Any()) return enumValue.ToString();
    
        var displayAttribute = memberInfo.GetCustomAttribute<DisplayAttribute>();
    
        if (displayAttribute == null) return enumValue.ToString();
    
        if (displayAttribute.ResourceType != null && displayAttribute.Name != null)
        {
            var manager = new ResourceManager(displayAttribute.ResourceType);
            return manager.GetString(displayAttribute.Name);
        }
    
        return displayAttribute.Name ?? enumValue.ToString();
    }
    

    示例

    public enum IndexGroupBy 
    {
        [Display(Name = "By Alpha")]
        ByAlpha,
        [Display(Name = "By Type")]
        ByType
    }
    

    这是它的用法:

    @IndexGroupBy.ByAlpha.DisplayName()
    

    编辑器模板

    这是一个编辑器模板,可以和上面的扩展方法一起使用:

    @model Enum
    
    @{    
        var listItems = Enum.GetValues(Model.GetType()).OfType<Enum>().Select(e =>
            new SelectListItem
            {
                Text = e.DisplayName(),
                Value = e.ToString(),
                Selected = e.Equals(Model)
            });
        var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
        var index = 0;
        ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
    
        foreach (var li in listItems)
        {
            var fieldName = string.Format(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;
    }
    

    这是一个示例用法:

    @Html.EditorFor(m => m.YourEnumMember, "Enum_RadioButtonList")
    

    【讨论】:

      【解决方案3】:

      解决方案来了 -

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

      第 1 步 -Views/Shared/EditorTemplates 目录中使用以下代码(来自上述参考的代码)创建 RadioButtonListEnum.cshtml 文件(如果不存在,然后创建该目录) -

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

      然后有你的枚举 -

      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
      }
      

      第 2 步 - 创建模型 -

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

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

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

      第 4 步 - 创建视图 -

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

      那么输出将是 -

      【讨论】:

      • 似乎有效。谢谢!!!如果在这些情况下也有内置的助手会很好,也许在未来的 MVC 版本中。但是仍然投票,我会接受答案!
      • 1+ 为您的努力 :)
      【解决方案4】:

      你可以使用下面的重载方法。

      @Html.Label(value.ToString(),"Cancel Invitation")
      

      这将呈现带有指定标签文本的标签,该标签作为上述调用中的第二个参数提供。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-16
        • 2021-11-30
        • 2013-11-18
        • 2013-07-05
        • 2017-08-21
        • 2018-02-16
        • 2015-08-07
        • 1970-01-01
        相关资源
        最近更新 更多