Enums to SelectList
So you have an Enum and you want to get a human readable SelectList. Well here is the code to do that. The caveat here is that your enum class must be decorated with a description attribute. T in this case is your type of enumeration. Use it like Eums.ToSelectList<InterestTypes>();
public static class Enums
{
public static SelectList ToSelectList<T>() {
var type = typeof (T);
if (type.IsEnum) {
var list = new List<object>();
var members = type.GetMembers(BindingFlags.Static | BindingFlags.Public | BindingFlags.GetField);
foreach (var memberInfo in members) {
var attribute = memberInfo.GetCustomAttributes(typeof (DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
var value = memberInfo.Name;
list.Add(attribute != null
? new {Text = attribute.Description, Value = value}
: new {Text = value, Value = value});
}
return new SelectList(list, "Value", "Text");
}
throw new Exception("this method is purely for enumerations.");
}
public static T Parse<T>(string input)
{
return (T)Enum.Parse(typeof (T), input, true);
}
}
public enum InterestTypes : int
{
[Description("Attractions")] Attraction = 1,
[Description("Events")] Event = 2,
[Description("Restaurants")] Restaurant = 4,
[Description("Schools")] SchoolDistrict = 5,
[Description("Featured Developments")] FeaturedDevelopment = 6,
[Description("Accommodations")] Accommodation = 7
}
I also threw in a generic enum parser helper for free, have fun.
