Question

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.

Was it helpful?

Solution

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;
        }

}

OTHER TIPS

You could use reflection to access properties of the attribute:

Type = SomethingType.Type2;

var memberInfo = Type.GetType().GetMember(Type.ToString());

if (memberInfo.Any())
{
    var attributes = memberInfo.First().GetCustomAttributes(typeof(DisplayAttribute), false);
    if (attributes.Any())
    {
        var name = ((DisplayAttribute)attributes.First()).Name;  // Type 2
    }
}

You can create a generic helper method that will read data from these attributes.

public static string GetAttributeValue<T>(this Enum e, Func<T, object> selector) where T : Attribute
    {

        var output = e.ToString();
        var member = e.GetType().GetMember(output).First();
        var attributes = member.GetCustomAttributes(typeof(T), false);

        if (attributes.Length > 0)
        {
            var firstAttr = (T)attributes[0];
            var str = selector(firstAttr).ToString();
            output = string.IsNullOrWhiteSpace(str) ? output : str;
        }

        return output;
    }

Example:

var x = SomethingType.Type1.GetAttributeValue<DisplayAttribute>(e => e.Name);

.......

class ModelClass
{
    public SomethingType Type { get; set; }

    public string TypeName
    {
        get { return Type.GetAttributeValue<DisplayAttribute>(attribute => attribute.Name); }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top