Created
October 2, 2012 13:26
-
-
Save bcronje/3819117 to your computer and use it in GitHub Desktop.
Enum ToSelectList extensions with DisplayAttribute support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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