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:

    <input id="Name_Foo" name="Name" type="radio" value="Foo" /><label for="Name_Foo" id="Name_Foo_Label">Foo</label>
    <input id="Name_Bar" name="Name" type="radio" value="Bar" /><label for="Name_Bar" id="Name_Bar_Label">Bar</label>

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

public static string RadioButtonList<T>(this IViewModelContainer<T> container, Expression<Func<T, object>> expression, IEnumerable<SelectListItem> items) where T : class
    TagBuilder divTag = new TagBuilder("div");
    foreach (var item in items)
        var radioTag = container.RadioButton(expression).Value(item.Value ?? item.Text).Checked(item.Selected).LabelAfter(item.Text);
        divTag.InnerHtml += radioTag;
    return divTag.ToString();

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:

<%=this.RadioButtonList(m => m.Name, new[] { "Foo", "Bar" })%>
Tweet Post Share Update Email RSS