Enums are handy. But they do not allow you have easy Text description on them.
How about using DisplayAttribuite on enum values and have that text in a drop-down? Easy!
/// <summary>
/// Creates a SelectList from Enum, taking Description values from Enum fields
/// Taken from here: http://stackoverflow.com/a/3705387/809357
/// </summary>
public static SelectList ToSelectListWithDisplayName<T>(this T enumeration, string selected = "")
{
var source = Enum.GetValues(typeof(T));
var items = new Dictionary<object, string>();
var displayAttributeType = typeof(DisplayAttribute);
foreach (var value in source)
{
FieldInfo field = value.GetType().GetField(value.ToString());
if (field == null) continue;
DisplayAttribute attrs = (DisplayAttribute)field.GetCustomAttributes(displayAttributeType, false).FirstOrDefault();
if (attrs != null)
{
items.Add((int)value, attrs.GetName());
}else // in case Description attribute is not available, we fall back to the default name
{
items.Add((int)value, value.ToString());
}
}
return new SelectList(items, "Key", "Value", selected);
}
Also you can get just on Display Name for one Enum Value:
public static string GetDisplayName(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
if (field == null)
return String.Empty;
object[] attribs = field.GetCustomAttributes(typeof(DisplayAttribute), true);
if(attribs.Length > 0)
{
return ((DisplayAttribute)attribs[0]).GetName();
}
return value.ToString();
}
