I've read up a good bit on creating a SelectList
from an Enum
to populate a drop down list, and found many solutions. Here are a few examples
public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
{
return (Enum.GetValues(typeof(T)).Cast<T>().Select(
enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
}
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
Both of these (and most others) return the names of the enum values for both Text
and Value
.
Example
public enum WeatherInIreland
{
NotGreat = 0,
Bad = 1,
Awful = 2
}
Results from the first two methods
<select id="Weather" name="Weather">
<option value="NotGreat">NotGreat</option>
<option value="Bad">Bad</option>
<option value="Awful">Awful</option>
</select>
However, I wanted to return the name for Text
and the int value for the Value
.
<select id="Weather" name="Weather">
<option value="0">NotGreat</option>
<option value="1">Bad</option>
<option value="2">Awful</option>
</select>
This is the code I came up with.
public static System.Web.Mvc.SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct, IComparable, IFormattable, IConvertible
{
List<SelectListItem> selist = new List<SelectListItem>();
foreach (int value in Enum.GetValues(typeof(TEnum)))
{
TEnum type = (TEnum)Enum.Parse(typeof(TEnum), value.ToString());
selist.Add(new SelectListItem { Value = value.ToString(), Text = type.ToString() });
}
return new System.Web.Mvc.SelectList(selist, "Value", "Text");
}
As you can see it's a modified version of the last method above. It works, but it is ugly. I have to iterate over the Enum
values as ints and then separately parse each one to return the name. Surely there's a better way of doing this?