Html Select From Enum
2/18/2009 12:08:28 AMCode for an ASP.net 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);
5:
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: }
Comments
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.
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.