I\'m using MVC and I have some RadioButtons in a foreach:
foreach (var item in group) {
-
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)
-
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)
-
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)
- 热议问题