C# 如何获取DataAnnotation显示名称?
我有EF模型课。为此,我为该分部类创建了MetadataType 现在我需要从c中读取或获取对象属性的所有这些displayname。因此,我可以使用Excel中的标题行C# 如何获取DataAnnotation显示名称?,c#,asp.net-mvc-4,data-annotations,C#,Asp.net Mvc 4,Data Annotations,我有EF模型课。为此,我为该分部类创建了MetadataType 现在我需要从c中读取或获取对象属性的所有这些displayname。因此,我可以使用Excel中的标题行 [MetadataType(typeof(vwGridMetadata))] public partial class vwGrid { } public class vwGridMetadata { [Display(Name = "Note ID")] public int intNoteID { ge
[MetadataType(typeof(vwGridMetadata))]
public partial class vwGrid
{
}
public class vwGridMetadata
{
[Display(Name = "Note ID")]
public int intNoteID { get; set; }
[Display(Name = "Global Number")]
public string strGlobalLoanNumber { get; set; }
[Display(Name = "Data Source ID")]
public Nullable<int> intDataSourceID { get; set; }
[Display(Name = "Sample ID")]
....
}
vwGrid grd=新vwGrid
在这里,我想得到迭代中的所有属性displayname。因此,我可以将它们添加到excel标题行和单元格中。怎么做?思考,林克是你的朋友
typeof(vwGridMetadata)
.GetProperties()
.Select(x => x.GetCustomAttribute<DisplayAttribute>())
.Where(x => x != null)
.Select(x => x.Name);
注意:为了使用这些方法,您需要在项目中包含System.Reflection和System.Linq名称空间。ASP.Net Core 2:
var listOfFieldNames = typeof(vwGridMetadata)
.GetProperties()
.Select(f => f.GetCustomAttribute<DisplayAttribute>())
.Where(x => x != null)
.Select(x=>x.Name)
.ToList();
只要这样做:
private string GetDisplayName(vwGridMetadata data, Object vwGridMetadataPropertie)
{
string displayName = string.Empty;
string propertyName = vwGridMetadataPropertie.GetType().Name;
CustomAttributeData displayAttribute = data.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");
if (displayAttribute != null)
{
displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
}
return displayName;
}
您可以创建一个foreach循环遍历vwGridMetadata类属性并对每个属性调用此方法,或者只在内部创建一个foreach并从方法中删除对象参数。嗨,朋友,这个问题已经在回答“查找链接”