获取DisplayName属性的所有值
我使用的是带有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但我有没有办法想法,扩展了这一码。
如果你真的不关心DisplayName
属性,但将(通过数据绑定实例)所使用的有效显示名称,最简单的就是用TypeDescriptor.GetProperties
方法:
var info = TypeDescriptor.GetProperties(typeof(Class1))
.Cast<PropertyDescriptor>()
.ToDictionary(p => p.Name, p => p.DisplayName);
你可以使用下面的代码 -
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);
}
}
我也提到了你在问题中提到的相同链接。
最终词典是作为 -
谢谢你的答案,但不幸的是你的代码不适用于我的项目。 – Cyr
是什么问题? – Dhanashree
它将displayName中的“Sequence contains no elements”返回到foreach循环中。 – Cyr
'DisplayName'或'Display'(它们是不同的)? –
@IvanStoev'DisplayName' – Cyr