Get the all the values of DisplayName attributes

Asked at 2016-12-15 14:02:53Z
  • 5 Subscribers

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.

2 answers in total

Ivan Stoev Posted at 2016-12-15 14:41:20Z

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);
Dhanashree Posted at 2016-12-15 14:55:13Z

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

Answer this questsion