I\'m trying to use the Html.DropDownList
extension method but can\'t figure out how to use it with an enumeration.
Let\'s say I have an enumeration like
I found an answer here. However, some of my enums have [Description(...)]
attribute, so I've modified the code to provide support for that:
enum Abc
{
[Description("Cba")]
Abc,
Def
}
public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper, string name, TEnum selectedValue)
{
IEnumerable values = Enum.GetValues(typeof(TEnum))
.Cast();
List items = new List();
foreach (var value in values)
{
string text = value.ToString();
var member = typeof(TEnum).GetMember(value.ToString());
if (member.Count() > 0)
{
var customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (customAttributes.Count() > 0)
{
text = ((DescriptionAttribute)customAttributes[0]).Description;
}
}
items.Add(new SelectListItem
{
Text = text,
Value = value.ToString(),
Selected = (value.Equals(selectedValue))
});
}
return htmlHelper.DropDownList(
name,
items
);
}
Hope that helps.