How to get the value in the [Display (Name = "")] attribute in the controller for any property using EF6

I am developing an MVC 5 application. I want to get the value in the [Display (Name = "")] attribute in my controller method for any property of any class.

My model:

public partial class ABC { [Required] [Display(Name = "Transaction No")] public string S1 { get; set; } } 

I looked at the answer to this question , but this is a small lengthy procedure. I am looking for something easily accessible and built-in.

So, I tried this:

 MemberInfo property = typeof(ABC).GetProperty(s); // s is a string type which has the property name ... in this case it is S1 var dd = property.CustomAttributes.Select(x => x.NamedArguments.Select(y => y.TypedValue.Value)).OfType<System.ComponentModel.DataAnnotations.DisplayAttribute>(); 

But I have 2 problems. At first, I do not get the value, that is, "No deal." And secondly, although I mentioned .OfType <> , I still get all the attributes, that is, [Display (Name = "")] and [Required].

But, fortunately, I get the value "Transaction No" in

property → CustomAttribute → [1] → NamedArguments → [0] → TypedValue → Value = "No transaction"

Since TypedValue.Value has the required value, how can I get it?

+6
source share
2 answers

This should work:

 MemberInfo property = typeof(ABC).GetProperty(s); var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute; if(dd != null) { var name = dd.Name; } 
+11
source

Alex Art's answer almost worked for me. dd.Name just returned the property name, but dd.GetName() returned the text from the Display attribute.

0
source

All Articles