Html Select From Enum

2/18/2009 12:08:28 AM

Code for an MVC extension method to generate a select from an enumeration.

   1:  public static string Select(this HtmlHelper html, string name, object value, Type enumType)
   2:  {
   3:      StringBuilder sb = new StringBuilder();
   4:      Type underlyingType = Enum.GetUnderlyingType(enumType);
   6:      sb.AppendFormat(@"<select name=""{0}"" id=""{1}"">", name, name.Replace('.', '_')); 
   7:      foreach (object option in Enum.GetValues(enumType))
   8:      {
   9:          sb.AppendFormat(@"<option value=""{0}""{1}>{2}</option>",
  10:              Convert.ChangeType(option, underlyingType),
  11:              value.Equals(option) ? " selected=\"selected\"" : "",
  12:              Enum.GetName(enumType, option));
  13:      }
  14:      sb.AppendFormat("</select>");
  15:      return sb.ToString();
  16:  }



7/7/2009 4:28:53 PM

Is there any advantage of using this approach rather than using HtmlHelper.DropdownList? The enum can be binded with this HtmlHelper as well. I am curious to know the reason behind this approach. Thanks.


7/25/2009 6:12:40 AM

I see what you are saying, and I think this may be a good feature request for the g:select tag. It should know when it is dealing with an enum to maybe have a different default value. Most of the time I use the GrailsUI AutoComplete instead of a g:select, but that can be a bit of a hardcore solution when g:select is so easy to markup.



6/1/2010 2:44:40 PM

Easier way:

public static MvcHtmlString EnumDropDownListFor(this HtmlHelper htmlHelper,Expression> expression)


IEnumerable values = Enum.GetValues(typeof(TEnum))


TEnum prop = expression.Compile().Invoke(htmlHelper.ViewData.Model);

IEnumerable items =

from value in values

select new SelectListItem


Text = value.ToString(),

Value = value.ToString(),

Selected = (value.Equals(prop))


return SelectExtensions.DropDownListFor(htmlHelper,expression,items);