[英]Can I get the DataAnnotation Display Name of a property when I don't know the type?
I am going to walk through the properties of items in an ICollection and at Compile Time will not necessarily know what type the items in the ICollection will be. 我将遍历ICollection中项目的属性,在编译时不一定会知道ICollection中项目的类型。 I can get the Property name, but would like to get the DataAnnotation Display Name (if any). 我可以获取属性名称,但是想要获取DataAnnotation显示名称(如果有)。
How can I find the Display Name defined in DataAnnotations (if any) of an unknown type at run time? 如何在运行时查找在数据类型注释(如果有)中定义的显示名称?
So far I have this: 到目前为止,我有这个:
foreach (var thisSection in Report.ReportSections)
{
reportBody.Append(thisSection.ReportSectionName + Environment.NewLine);
if (thisSection.ReportItems != null)
{
var itemType = thisSection.ReportItems.GetType().GetGenericArguments().Single();
var first = true;
foreach (var prop in itemType.GetProperties())
{
if (!first) reportBody.Append(",");
// This gives me the property name like 'FirstName'
reportBody.Append(prop.Name);
try
{
// I'd like to get the Display Name from
// [Display(Name = "First Name")]
var displayName = prop.GetCustomAttributes();
}
catch (Exception e)
{
}
first = false;
}
reportBody.Append(Environment.NewLine);
}
}
ReportSection
is defined like this: ReportSection
的定义如下:
public interface IReportSection
{
string ReportSectionName { get; }
ICollection ReportItems { get; }
}
The ICollection could contain a collection of objects like this: ICollection可以包含这样的对象的集合:
public class ProjectAffiliateViewModel
{
public string Role { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
}
For the Role
property we would get Role
, and for the FirstName
property we would get First Name
. 对于Role
属性,我们将获得Role
;对于FirstName
属性,我们将获得First Name
。
Like this: 像这样:
DisplayAttribute attribute = prop.GetCustomAttributes(typeof(DisplayAttribute), false)
.Cast<DisplayAttribute>()
.SingleOrDefault();
string displayName = (attribute != null) ? attribute.Name : prop.Name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.