mvc radiobuttons in foreach

后端 未结 3 862
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 13:31

I\'m using MVC and I have some RadioButtons in a foreach:

    foreach (var item in group) {
                    
                                 


        
相关标签:
3条回答
  • 2020-12-14 13:45

    Don't write loops in views. They are ugly and you end up with undesired behavior as the one described in your question. Use editor templates, like this:

    <table>
        <thead>
            <tr>
                <th>Approved status</th>
            </tr>
        </thead>
        <tbody>
             @Html.EditorFor(x => x.Groups)
        </tbody>
    </table>
    

    Here I assume that your view model has a Groups collection property of type IEnumerable<GroupViewModel>. Now all that's left is to write the corresponding editor template which will be executed for each element in the Groups collection (~/Views/Shared/EditorTemplates/GroupViewModel.cshtml):

    @model GroupViewModel
    <tr>
        <td>
            @Html.RadioButtonFor(x => x.CheckerApproved, "true") <span>Approved</span>
            @Html.RadioButtonFor(x => x.CheckerApproved, "false") <span>Not approved</span>
        </td>
    </tr>
    

    Now not only that you no longer need to write any ugly foreach loops in your view but you end up with correct naming convention.

    0 讨论(0)
  • 2020-12-14 13:54

    One way how to use radiobuttons in foreach

     @{
        int i = 0;
        foreach(var item in group)
          { 
             i++;
           <tr>
           <td>
              <input id="item_CheckerApproved" type="radio" value="True" name="item.CheckerApproved_@i">
              <input id="item_CheckerApproved" type="radio" value="False" name="item.CheckerApproved_@i 
                 checked="checked">
           </td>
        </tr>
    
        <tr>
           <td>
              <input id="item_CheckerApproved" type="radio" value="True" name="item.CheckerApproved_@i">
              <input id="item_CheckerApproved" type="radio" value="False" name="item.CheckerApproved_@i 
                 checked="checked">
           </td>
        </tr>
          }
    
        }
    

    Hope it helps ;)

    0 讨论(0)
  • 2020-12-14 13:55

    One way is to use a for loop and RadioButton instead of RadioButtonFor

    @for (int i = 0; i < item.Count; i++)
    {
        <tr>
            <td>
                @Html.RadioButton("item_CheckerApproved_" + i, true, item[i].CheckerApproved)
                @Html.RadioButton("item_CheckerApproved_" + i, false, !item[i].CheckerApproved)
            </td>
        </tr>
    }
    
    0 讨论(0)
提交回复
热议问题