I am new to asp.net MVC. I am trying to use dropdown control on my view page, which populates from enum. I also want to add custom descriptions to dropdown values. I searched so
Given :
public enum MyEnum
{
[Description("This is the description if my member A")]
A,
[Description("This is the description if my member B")]
B
}
I personally use this extension method to get a description from my enum:
public static string GetDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
To use it:
MyEnum.A.GetDescription();
Hope this help.