2013-01-10 19 views
3

在Ruby on Rails中,配置中有一個YAML文件,可讓您定義模型屬性名稱的純英文版本。實際上,它可以讓你定義任何簡單的語言版本:它是國際化的一部分,但大多數人使用它來將模型驗證結果顯示給用戶。.NET中的用戶友好屬性名稱,如Rails中的那些

我需要.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’,當也許‘訂貨人用戶名’會更好。 .NET中有這樣的東西嗎?

回答

7

有一個名爲DisplayName的數據屬性,它允許你這樣做。只需用此標註您的模型屬性並輸入友好名稱

[DisplayName("Full name")] 
public string FullName { get; set; } 
+4

如果你需要訪問通過反射(如問題問),其屬性,你會在[CustomAttributes(http://msdn.microsoft.com/發現PropertyInfo的屬性。 – Clemens

+0

+1,如果您需要更多數據 - 您始終可以創建自定義屬性,爲每個字段添加更多(可選)元數據。 –

+0

在這個答案中加入'@ Html.DisplayFor()'語法是很值得指出如何輕鬆訪問它的。 – Bobson

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>";