Get the all the values of DisplayName attributes c# data-annotations entity-framework-6


I'm using MVC 5 with EntityFramework 6 DataAnnotations. I would like to know if there is a way to get all DisplayName of an object and save them in a variable into a Controller class.

For example, considering the class:

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

How to get the values of DisplayName for all attributes? For example how to create a function that returns a Dictionary< string,string > which has a key with attribute name and value with DisplayName, like this:

{ "Id": "The ID name", "Value": "My Value", "Label": "Label name to display"}.

I have seen this topic stackoverflow - get the value of DisplayName attribute but I have no ideas of a way to extends this code.

7/16/2017 12:58:57 AM

Accepted Answer

If you don't really care for the DisplayName attribute, but the effective display name that will be used (for instance by data binding), the easiest is to use TypeDescriptor.GetProperties method:

var info = TypeDescriptor.GetProperties(typeof(Class1))
    .ToDictionary(p => p.Name, p => p.DisplayName);
12/15/2016 2:41:20 PM

Popular Answer

You can use the code below -

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

I have also referred to same link that you have mentioned in the question.

the final dictionary is as -

enter image description here

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow