Html Select From Enum

2/18/2009 12:08:28 AM

Code 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

Altaf

Altaf

http://www.altafkhatri.com/
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.

geetanjli

geetanjli

http://www.slotswebsites.net/
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.

bryan

bryan

6/1/2010 2:44:40 PM

Easier way:

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

{

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

.Cast();

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);

}

personal statement writing

personal statement writing

http://www.personalstatementwriters.com
1/16/2012 10:14:34 AM

Thank you for this great information, you write very well which i like very much. I really impressed by your post.

SEO Services India

SEO Services India

http://www.sonicinfosystem.com
1/25/2012 7:18:27 AM

I wonder how you got so good. This is really a fascinating blog, lots of stuff that I can get into. One thing I just want to say is that your Blog is so perfect!

affordable term life insurance

affordable term life insurance

http://www.everydaylifeinsurance.org/affordable-life-insurance/
1/30/2012 4:55:58 AM

Very useful post. I hope you will continue your same best work and we will get more informative post which can helpful to us. Thanks for this.

Add Comment