4

I have tried to group a set of radio buttons inside loop by providing additional html attribute in html help as below -

<ol class="Opt">
    @foreach (var opt in quest.Options)
    {
        <li class="Opt">
            @Html.RadioButtonFor(o => opt.Title, opt.Title, new { @name = "uniqueRadio"})
            @Html.Label(opt.Title)
        </li>
    }
</ol>

However name attribute ot generated input html tag gets over-written by opt.Title for obvious reasons. MVC-4 uses name attribute for strongly typed model-binding when posting data.

How do I make radio button grouped together ?

EDIT: I replaced RadioButtonFor with RadioButton, as suggested below. But this way I miss-out model binding feature.

<ol class="Question">
    @for (int j = 0; j < Model.Options.Count; j++)
    {
        <li class="Opt">                    
            @Html.RadioButton("uniqueRadio", Model.Options[j].IsSelected, false)
            @Model.Options[j].Title
        </li>
    }
</ol>
Abhijeet
  • 13,562
  • 26
  • 94
  • 175
  • Have you tried this http://stackoverflow.com/questions/5289489/mvc-radio-button-lists-are-not-grouped-when-using-the-htmlhelper-class?rq=1 – ckv Aug 04 '13 at 07:32
  • possible duplicate of [How can I create a RadioButtonList in a MVC View via HTML class ( Razor syntax )](http://stackoverflow.com/questions/6132474/how-can-i-create-a-radiobuttonlist-in-a-mvc-view-via-html-class-razor-syntax) – Imad Alazani Aug 04 '13 at 08:29
  • this link may help you working on a answer myself: http://dolinked.com/questions/2498099/nested-for-loops-radiobuttonfor-not-working – Pakk Aug 31 '15 at 13:26

1 Answers1

4

Use simple RadioButton

<ol class="Opt">
    @foreach (var opt in quest.Options)
    {
        <li class="Opt">
            @Html.RadioButton("uniqueRadio", opt.Title)
            @Html.Label(opt.Title)
        </li>
    }
</ol
sergioadh
  • 1,461
  • 1
  • 16
  • 24
  • 1
    I think it should be `@Html.RadioButton("uniqueRadio", opt.Title)` because the first parameter of the helper is the name – Daniele Aug 04 '13 at 09:34
  • @Daniele, by using simple radio button I miss-out default model binding feature, on post action, right ? – Abhijeet Aug 05 '13 at 04:39
  • not exactly, if you set the name of your RadioButton to Title and your view is expecting a Title boolean it will bind to it. – sergioadh Aug 05 '13 at 04:47