4

在 Ruby on Rails 中,配置中有一个 YAML 文件,可让您定义模型属性名称的纯英文版本。实际上,它可以让你定义简单的任何语言版本:它是国际化的一部分,但大多数人使用它来向用户显示模型验证结果。

我的 .NET MVC 4 项目中需要这种功能。用户提交一个表单并收到一封包含他们发布的几乎所有内容的电子邮件(表单绑定到模型)。我编写了一个辅助方法来通过反射转储出属性/值对的 HTML 表,例如

foreach (PropertyInfo info in obj.GetType()
    .GetProperties(BindingFlags.Public | 
                   BindingFlags.Instance | 
                   BindingFlags.IgnoreCase)) 
{
  if (info.CanRead && !PropertyNamesToExclude.Contains(info.Name)) 
  {
    string value = info.GetValue(obj, null) != null ? 
                                            info.GetValue(obj, null).ToString() :
                                            null;
    html += "<tr><th>" + info.Name + "</th><td>" + value + "</td></tr>";
  }
}

但是,当然,这打印出来info.Name就像“OrdererGid”,而“Orderer Username”可能会更好。.NET中有这样的东西吗?

4

2 回答 2

10

There is a data attribute called DisplayName which allows you to do this. Just annotate your model properties with this and a friendly name for each

[DisplayName("Full name")]
public string FullName { get; set; }
于 2013-01-10T22:34:17.127 回答
1

非常感谢@Stokedout 和@Clemens 的回答。实际上通过反射访问有点复杂。由于某种原因,我无法直接访问 CustomAttributes 属性。终于来到了这个:

DisplayNameAttribute dna = (DisplayNameAttribute)info
    .GetCustomAttributes(typeof(DisplayNameAttribute), true).FirstOrDefault();

string name = dna != null ? dna.DisplayName : info.Name;

string value = info.GetValue(obj, null) != null ? 
     (info.GetValue(obj, null).GetType().IsArray ? 
           String.Join(", ", info.GetValue(obj, null) as string[]) : 
           info.GetValue(obj, null).ToString()) : 
      null;

html += "<tr><th>" + name + "</th><td>" + value + "</td></tr>";
于 2013-01-11T22:01:58.437 回答