2016-12-15 98 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