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?
This should work:
MemberInfo property = typeof(ABC).GetProperty(s);
var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
if(dd != null)
{
var name = dd.Name;
}
You can use it:
MemberInfo property = typeof(ABC).GetProperty(s);
var name = property.GetCustomAttribute<DisplayAttribute>()?.Name;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With