您可以为 Enum DropdownList 创建自己的模板。这是我使用的一个,它使用扩展方法从属性中获取值,而不仅仅是枚举的名称:
把它放在 Views/Shared/EditorTemplates 目录中,作为EnumDropdown.cshtml
@model Enum
@{
var sort = (bool?)ViewData["sort"] ?? false;
var enumValues = new List<object>();
foreach (var val in Enum.GetValues(Model.GetType()))
{
enumValues.Add(val);
}
}
@Html.DropDownListFor(m => m,
enumValues
.Select(m =>
{
string enumVal = Enum.GetName(Model.GetType(), m);
var display = m.GetDescription() ?? enumVal;
return new SelectListItem()
{
Selected = (Model.ToString() == enumVal),
Text = display,
Value = enumVal
};
})
.OrderBy(x => sort ? x.Text : null)
,new { @class = "form-control" })
这是GetDescription()的代码:
public static string GetDescription(this object enumerationValue)
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
下面的示例用法。型号:
public enum MyEnum
{
[Description("The First Option1")]
Option1,
Option2
}
public class MyModel
{
[UIHint("EnumDropdown")] //matches EnumDropdown.cshtml
public MyEnum TheEnum { get; set; }
}
查看
@model MyModel
@Html.EditorFor(x => x.TheEnum)
将创建一个带有选项“第一个选项”和“选项 2”的下拉列表