Skip to content

@bcronje /gist:3819117
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Enum ToSelectList extensions with DisplayAttribute support
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.