你需要得到显示名(DisplayAttribute)从枚举, 检查实施例下面以设置枚举显示说明属性
动作(结合下拉列表)
public ActionResult Index()
{
var enumDataColours = from CSSColours e in Enum.GetValues(typeof(CSSColours))
select new
{
ID = StaticHelper.GetDescriptionOfEnum((CSSColours)e),
Name = e.ToString()
};
ViewBag.EnumColoursList = new SelectList(enumDataColours, "ID", "Name");
return View();
}
Helper方法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)
枚举
public enum CSSColours
{
[Display(Description = "bg-green")]
Green,
[Display(Description = "bg-blue")]
Blue,
}
它的讨论http://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via -mvc-razor-code – cutit