C# 值为Enum Display Description属性的MVC EnumDropDownListFor
我有一个具有显示描述属性的枚举C# 值为Enum Display Description属性的MVC EnumDropDownListFor,c#,asp.net-mvc,razor,enums,C#,Asp.net Mvc,Razor,Enums,我有一个具有显示描述属性的枚举 public enum CSSColours { [Display(Description = "bg-green")] Green, [Display(Description = "bg-blue")] Blue, } 现在我想将这个枚举绑定到DropDownlist,在下拉项显示文本中显示枚举值(绿色,蓝色),并将描述作为项值(绿色,蓝色) 当我使用EnumDropDownLi
public enum CSSColours
{
[Display(Description = "bg-green")]
Green,
[Display(Description = "bg-blue")]
Blue,
}
现在我想将这个枚举绑定到DropDownlist,在下拉项显示文本中显示枚举值(绿色,蓝色),并将描述作为项值(绿色,蓝色)
当我使用EnumDropDownListFor
helper方法绑定下拉列表时
@Html.EnumDropDownListFor(c => dm.BgColor)
它将项值设置为枚举值(0,1),但找不到将值设置为显示说明的方法
如何设置枚举显示描述属性的值?您需要从枚举中获取显示名称(DisplayAttribute), 选中下面的示例以设置“枚举显示说明”属性的值 操作(绑定下拉列表) 助手方法GetDescriptionOfEnum通过枚举名称获取描述属性
public static class StaticHelper
{
public static string GetDescriptionOfEnum(Enum value)
{
var type = value.GetType();
if (!type.IsEnum) throw new ArgumentException(String.Format("Type '{0}' is not Enum", type));
var members = type.GetMember(value.ToString());
if (members.Length == 0) throw new ArgumentException(String.Format("Member '{0}' not found in type '{1}'", value, type.Name));
var member = members[0];
var attributes = member.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false);
if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' doesn't have DisplayAttribute", type.Name, value));
var attribute = (System.ComponentModel.DataAnnotations.DisplayAttribute)attributes[0];
return attribute.Description;
}
}
剃刀视图
@Html.DropDownList("EnumDropDownColours", ViewBag.EnumColoursList as SelectList)
枚举
讨论过,在这个答案中,我唯一要更改的是将DropDownList更改为DropDownListFor,如下所示:“@Html.DropDownListFor(m=>m.CSSColour,ViewBag.CSSColours as SelectList,“Select One”)”
@Html.DropDownList("EnumDropDownColours", ViewBag.EnumColoursList as SelectList)
public enum CSSColours
{
[Display(Description = "bg-green")]
Green,
[Display(Description = "bg-blue")]
Blue,
}