Posts
208
Comments
1144
Trackbacks
51
MVC RadioButtonList HTML Helper – Take 2

Yesterday I posted a solution for creating a RadioButtonList HTML helper.  But upon closer examination, I’ve come to the conclusion that for a horizontal flow of radio buttons, an HTML table is really not the way to go.  Perhaps a remnant from the days of web forms past. Based on a conversation I had with a co-worker, HTML output like this would be much better:

   1:  <div>
   2:      <input id="Name_Foo" name="Name" type="radio" value="Foo" /><label for="Name_Foo" id="Name_Foo_Label">Foo</label>
   3:      <input id="Name_Bar" name="Name" type="radio" value="Bar" /><label for="Name_Bar" id="Name_Bar_Label">Bar</label>
   4:  </div>

Not only does this produce better HTML, it also allows me to simplify the C# code:

   1:  public static string RadioButtonList<T>(this IViewModelContainer<T> container, Expression<Func<T, object>> expression, IEnumerable<SelectListItem> items) where T : class
   2:  {
   3:      TagBuilder divTag = new TagBuilder("div");
   4:   
   5:      foreach (var item in items)
   6:      {
   7:          var radioTag = container.RadioButton(expression).Value(item.Value ?? item.Text).Checked(item.Selected).LabelAfter(item.Text);
   8:          divTag.InnerHtml += radioTag;
   9:      }
  10:      return divTag.ToString();
  11:  }

This still gives me all the benefits from the original post including correct “id” and “name” attributes while being able to call it in one line of code like this:

   1:  <%=this.RadioButtonList(m => m.Name, new[] { "Foo", "Bar" })%>
posted on Thursday, August 6, 2009 8:36 AM Print
Comments
Gravatar
# re: MVC RadioButtonList HTML Helper – Take 2
Ed
9/7/2011 1:42 PM
IViewModelContainer ??

Where is that located?
Gravatar
# re: MVC RadioButtonList HTML Helper – Take 2
Steve
9/7/2011 1:45 PM
It's part of MvcContrib (at least it was at the time of this post) in the FluentHtml section (which is what this blog post was based on).

Post Comment

Title *
Name *
Email
Comment *  
Verification

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud