Does anyone know how to access the "Display Name" data annotation of enum types?
I have an enum type with display names
class enum SomethingType {
[Display(Name = "Type 1")]
Type1,
[Display(Name = "Type 2")]
Type2
}
and a model class that references to it
class ModelClass {
public SomethingType Type {get; set;}
}
How do I display the display name for the values in ModelClass?
Thanks.
I think you are looking for something like this:
class ModelClass
{
public SomethingType MyType {get; set;}
public string TypeName {
get
{
var enumType = typeof(SomethingType);
var field = enumType.GetFields()
.First(x => x.Name == Enum.GetName(enumType, MyType));
var attribute = field.GetCustomAttribute<Display>();
return attribute.Name;
}
}
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