11

This is my enum.

public enum ContractType
{
    [Display(Name = "Permanent")]
    Permanent= 1,

    [Display(Name = "Part Time")]
    PartTime= 2,

}

I try to get display name using below code.

 string x = Enum.GetName(typeof(ContractType), 2);

But it is return "PartTime" always. Actually I want to get the name of display attribute. For above example x should be assigned Part Time

I saw there are solutions which having huge code. Doesn't this have a simple/one line solution?

Please show me a direction.

weeraa
  • 1,123
  • 8
  • 23
  • 40
  • 5
    http://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via-mvc-razor-code – Valentin Dec 06 '16 at 12:39

1 Answers1

26

Given an enum

public enum ContractType
{
   [Display(Name = "Permanent")]
   Permanent= 1,

   [Display(Name = "Part Time")]
   PartTime //Automatically 2 you dont need to specify
}

Custom method to get the data annotation display name.

//This is a extension class of enum
public static string GetEnumDisplayName(this Enum enumType)
{
    return enumType.GetType().GetMember(enumType.ToString())
                   .First()
                   .GetCustomAttribute<DisplayAttribute>()
                   .Name;
}

Calling GetDisplayName()

ContractType.Permanent.GetEnumDisplayName();

Hope this helps :)

dijam
  • 658
  • 1
  • 9
  • 21