Helper Method for the Helper Method

As you may know from my previous post, I am actively working on an ASP.Net MVC web site for the Ronald McDonald House of Iowa. I just wrote a helper function that turned out to be very useful for me.

Several of the model objects in our application are fields where the end user has to select one item from a list. Since these lists are very static, I coded them in the system as Enums and stored the integer values in the database. This left me with the requirement to build a drop down list box on the data entry form with the textual values of the Enum displayed but the integer values as the "value" for each selection.

There is already a helper method to build drop down list controls and it seems to work quite well. However, it requires a List<SelectListItem> as a parameter and I have an Enum. So, I made a helper to help with the helper.

The following function converts an Enum into a List<SelectListItem> for use with the HtmlHelper.DrowDown() helper function.

public static List<SelectListItem> GetDropDownListFromEnum(Type enumType)
{
   List<SelectListItem> items = new List<SelectListItem>();
   var labels = Enum.GetNames(enumType);
   var values = Enum.GetValues(enumType);
   for (int i = 0; i < labels.Length; i++)
   {
       SelectListItem i1 = new SelectListItem();
       i1.Value = ((int)values.GetValue(i)).ToString();
       i1.Text = labels[i];
       items.Add(i1);
   }
   return items;
}

This essentially allows me to take this Enum:

public enum Priority
{
   None = 0,
   Minimal = 10,
   Low = 20,
   Medium = 30,
   High = 40,
   Important = 50
}

And use the following code to render it as a drop down list in the page.

<%
   List<SelectListItem> statusItems = ModelHelpers.GetDropDownListFromEnum(typeof(Status));
%>
<div class="FormField">
  <label> Priority: </label>
   <%= Html.DropDownList("priority", priorityItems)%>
</div>

Hope you enjoy!