Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DataAnnotation Display Name?

I have EF model class. for that I created MetadataType for that partial class.

Now I need to read or get all of these displayname of the properties of the object from c#. So I can use the in Excel Header row.

[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 = new vwGrid;

Here I want get all properties displayname in iteration. So I can add them to excel Header row and cells. How to do that?

like image 567
James123 Avatar asked May 12 '14 13:05

James123


2 Answers

Reflection and LINQ is your friend

typeof(vwGridMetadata)
.GetProperties()
.Select(x => x.GetCustomAttribute<DisplayAttribute>())
.Where(x => x != null)
.Select(x => x.Name);

Note: You need to include System.Reflection and System.Linq namespaces to your project in order to use these methods.

like image 65
Selman Genç Avatar answered Nov 20 '22 05:11

Selman Genç


ASP.Net Core 2 :

 var listOfFieldNames = typeof(vwGridMetadata)
                    .GetProperties()
                    .Select(f => f.GetCustomAttribute<DisplayAttribute>())
                    .Where(x => x != null)
                    .Select(x=>x.Name)
                    .ToList();
like image 33
masoud Avatar answered Nov 20 '22 04:11

masoud