msgbartop
Clean cut, oder free, poor speller
msgbarbottom

16 Jan 12 Razor DropDownList With Descriptions From An Enum Using Extentions, Generics, and Reflection.

A good test of a web framework is to see how it handles select boxes.  It requires managing the list, the selected item across several states,  be easily styled, be easily ajax-ed, and connect to a data store.

I like using Enums for static data, but they are a bit limited without a description value, you end up with select options labeled “ItemName ” instead of  ”Human Friendly Item Name”.

Binding an enum to a dropdown is well documented. Adding descriptions to enums is also well documented.  Here is a way to have enums with descriptions into a dropdown.

 

Your Enum

 public enum ProjectRoles { [Description("Descision Maker")]DescisionMaker, Researcher, [Description("Project Manager")]ProjectManager };

 

The Razor

 @Html.DropDownListFor(model => model.YourRole, EnumUtils.ToSelectList<ContactModel.ProjectRoles>(Model.YourRole.ToString()));

 

This function will turn your enum into an IEnumerable<SelectListItem>

public static IEnumerable<SelectListItem> ToSelectList<T>(string selectedvalue)
{
if (!typeof(T).IsEnum) throw new ArgumentException(“T must be an enumerated type”);
return Enum.GetValues(typeof(T))
.OfType<T>()
.Select(x => new SelectListItem()
{
Value = x.ToString(),
Text = (typeof(T)
.GetField(x.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.OfType<DescriptionAttribute>()
.FirstOrDefault() ?? new DescriptionAttribute(x.ToString())
).Description,
Selected = x.ToString() == (selectedvalue ?? “”)
});
}

 

Of course shortly after finishing this I found a great post on StackOverflow about making html helpers which results in an even prettier finish in razor, but requires a few extra helpers.

Comments are closed.