2016-12-15 202 views
0

我使用的是帶有EntityFramework 6 DataAnnotations的asp.net MVC 5。 我想知道是否有辦法讓一個對象的所有DisplayName並將它們保存在一個變量到一個控制器類。獲取DisplayName屬性的所有值

例如,考慮到類:

public class Class1 
{ 
    [DisplayName("The ID number")] 
    public int Id { get; set; } 

    [DisplayName("My Value")] 
    public int Value { get; set; } 

    [DisplayName("Label name to display")] 
    public string Label { get; set; } 
} 

如何獲得的DisplayName值的所有屬性?例如如何創建一個返回Dictionary< string,string >它與屬性名稱和價值的關鍵與DisplayName的功能,如:

{ "Id": "The ID name", "Value": "My Value", "Label": "Label name to display"}. 

我已經看到了這個話題stackoverflow - get the value of DisplayName attribute但我有沒有辦法想法,擴展了這一碼。

+0

'DisplayName'或'Display'(它們是不同的)? –

+0

@IvanStoev'DisplayName' – Cyr

回答

2

如果你真的不關心DisplayName屬性,但將(通過數據綁定實例)所使用的有效顯示名稱,最簡單的就是用TypeDescriptor.GetProperties方法:

var info = TypeDescriptor.GetProperties(typeof(Class1)) 
    .Cast<PropertyDescriptor>() 
    .ToDictionary(p => p.Name, p => p.DisplayName); 
+0

謝謝你的回答。我已經封裝了用於使用泛型類的代碼並繼續工作。你解決了我的問題! – Cyr

+0

@Cyr,因此將其標記爲答案 –

+0

是否可以使用顯示名稱的值以及對函數本身的引用來獲取字典?即使這隻適用於靜態方法。 – Reiner

0

你可以使用下面的代碼 -

Class1 c = new Class1(); 
PropertyInfo[] listPI = c.GetType().GetProperties(); 
Dictionary<string, string> dictDisplayNames = new Dictionary<string, string>(); 
string displayName = string.Empty; 

foreach (PropertyInfo pi in listPI) 
{ 
    DisplayNameAttribute dp = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault(); 
      if (dp != null) 
      { 
       displayName = dp.DisplayName; 
       dictDisplayNames.Add(pi.Name, displayName); 
      } 
} 

我也提到了你在問題中提到的相同鏈接。

最終詞典是作爲 -

enter image description here

+0

謝謝你的答案,但不幸的是你的代碼不適用於我的項目。 – Cyr

+0

是什麼問題? – Dhanashree

+0

它將displayName中的「Sequence contains no elements」返回到foreach循環中。 – Cyr