Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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

My model is as:

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

I have looked answer to this question, but it is a little lengthy procedure. I am looking for something readily available and built-in.

So, I have 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, First I am not getting the value i.e. "Transaction No". And secondly even though I have mentioned .OfType<> I am still getting all attributes i.e. [Display(Name="")] and [Required].

But luckily I am getting the "Transaction No" value in

property>>CustomAttribute>>[1]>>NamedArguments>>[0]>>TypedValue>>Value = "Transaction No"

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

like image 359
Awais Mahmood Avatar asked Sep 27 '15 12:09

Awais Mahmood


3 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;
}
like image 188
Alex Art. Avatar answered Nov 20 '22 18:11

Alex Art.


You can use it:

MemberInfo property = typeof(ABC).GetProperty(s); 
var name = property.GetCustomAttribute<DisplayAttribute>()?.Name;
like image 5
Ahmed Galal Avatar answered Nov 20 '22 19:11

Ahmed Galal


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

like image 2
Marc Levesque Avatar answered Nov 20 '22 19:11

Marc Levesque