枚举的显示名称是这样的
这是示例
public enum Technology
{
[Display(Name = "AspNet Technology")]
AspNet,
[Display(Name = "Java Technology")]
Java,
[Display(Name = "PHP Technology")]
PHP,
}
和这样的方法
public static string GetDisplayName(this Enum value)
{
var type = value.GetType();
var members = type.GetMember(value.ToString());
if (members.Length == 0) throw new ArgumentException(String.Format("error '{0}' not found in type '{1}'", value, type.Name));
var member = members[0];
var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' doesn't have DisplayAttribute", type.Name, value));
var attribute = (DisplayAttribute)attributes[0];
return attribute.GetName();
}
而你的控制器是这样的
public ActionResult Index()
{
string DisplayName = Technology.AspNet.GetDisplayName();
return View();
}
对于类属性,请按照此步骤
public static string GetDisplayName2<TSource, TProperty> (Expression<Func<TSource, TProperty>> expression)
{
var attribute = Attribute.GetCustomAttribute(((MemberExpression)expression.Body).Member, typeof(DisplayAttribute)) as DisplayAttribute;
return attribute.GetName();
}
并像这样在您的控制器中调用此方法
// Class1 is your classname and firstname is your property of class
string localizedName = Testing.GetDisplayName2<Class1, string>(i => i.firstname);