2

是否可以访问控制器中参数的显示名称?例如,假设我将参数定义为

public class Class1
{
  [DisplayName("First Name")]
  public string firstname { get; set; }
}

我现在希望能够在我的控制器中访问 firstname 的显示名称。就像是

string name = Model.Class1.firstName.getDisplayName();

有没有类似的方法getDisplayName()可以用来获取显示名称?

4

3 回答 3

4

首先,您需要获取一个表示该属性的 MemberInfo 对象。您将需要进行某种形式的反思:

MemberInfo property = typeof(Class1).GetProperty("Name");

(我使用的是“旧式”反射,但如果您可以在编译时访问该类型,也可以使用表达式树)

然后您可以获取属性并获取 DisplayName 属性的值:

var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute), true)
      .Cast<DisplayNameAttribute>().Single();
string displayName = attribute.DisplayName;
于 2013-01-14T07:58:23.773 回答
1

在此链接中找到了答案。我创建了一个 Html 帮助类,将其命名空间添加到我的视图 web.config 并在我的控制器中使用它。所有在链接中描述

于 2013-01-14T13:11:43.153 回答
0

枚举的显示名称是这样的

这是示例

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);
于 2016-09-05T16:10:59.753 回答