13

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?

1

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"Do not use this property to get the value of the Name property. Use the GetName method instead." learn.microsoft.com/en-us/dotnet/api/…
2

ASP.Net Core 2 :

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

Comments

0

Just do this:

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;
}

You can make a foreach to loop through vwGridMetadata class properties and call this method on each property, or just make a foreach inside and remove the Object argument from the method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.