public
Created

Enum ToSelectList extensions with DisplayAttribute support

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
public static class EnumExtensions
{
public static SelectList ToSelectList<T>(T? defaultValue) where T : struct
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = from Enum e in Enum.GetValues(t)
select new
{
ID = Enum.Parse(typeof(T), e.ToString()),
Description = GetEnumDescription(e)
};
 
if (defaultValue.HasValue)
return new SelectList(values, "ID", "Description", Enum.Parse(typeof(T), defaultValue.ToString()));
else
return new SelectList(values, "ID", "Description");
}
return null;
}
 
public static string GetEnumDescription<T>(T value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
 
DisplayAttribute[] attributes = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false);
 
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Name;
else
return value.ToString();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.