问题
I have a dynamic forms with checkbox/radio-button lists & matrices:
Following code renders checkbox list:
@foreach (var sq in Model.SubQuestions)
{
<label>
<input type="hidden" name="answerResult.index" value="@sq.Id" />
<input type="checkbox" name="answerResult[@sq.Id].SubQuestionId" value="@sq.Id" />
@sq.Label.Name
</label>
}
radio-button list:
<input type="hidden" name="answerResult.index" value="@Model.Id" />
@foreach (var sq in Model.SubQuestions)
{
<label>
<input type="radio" name="answerResult[@Model.Id].SubQuestionId" value="@sq.Id" />
@sq.Label.Name
</label>
}
My POST-action in controller:
[HttpPost]
public ActionResult PassageSurvey(int surveyId, int surveyPageIndex, IList<AnswerResult> answerResult)
where IList<AnswerResult>
is an auto-bound collection from my form. I get only items that were checked/selected. Everything is going well.
Now I need to get the same collection from checkbox/radio-button matrices.
Radio-button matrix:
<table width="100%">
<tr>
<th></th>
@foreach (var av in Model.AnswerVariants)
{
<th style="text-align: center;">
<label>@av.Label.Name</label>
</th>
}
</tr>
@foreach (var sq in Model.SubQuestions)
{
<tr>
<td>
<label>@sq.Label.Name</label>
<input type="hidden" name="answerResult.index" value="@sq.Id" />
<input type="hidden" name="answerResult[@sq.Id].SubQuestionId" value="@sq.Id" />
</td>
@foreach (var av in Model.AnswerVariants)
{
<td align="center">
<input type="radio" name="answerResult[@sq.Id].AnswerVariantId" value="@av.Id" />
</td>
}
</tr>
}
</table>
Checkbox matrix:
<table width="100%">
<tr>
<th></th>
@foreach (var av in Model.AnswerVariants)
{
<th style="text-align: center;">
<label>@av.Label.Name</label>
</th>
}
</tr>
@foreach (var sq in Model.SubQuestions)
{
<tr>
<td>
<label>@sq.Label.Name</label>
</td>
@foreach (var av in Model.AnswerVariants)
{
<td align="center">
<input type="hidden" name="answerResult.index" value="@sq.Id" />
<input type="hidden" name="answerResult[@sq.Id].AnswerVariantId" value="@sq.Id" />
<input type="checkbox" name="answerResult[@sq.Id].SubQuestionId" value="@sq.Id" />
</td>
}
</tr>
}
</table>
POST-action in controller always the same.
Now from radio-button matrix (in current sample 3x3) IList<AnswerResult>
gets always 3 items, depending on items that were selected in rows and columns.
But from Checkbox matrix (3x3) IList<AnswerResult>
gets always all 9 items (regardless items were checked, hidden-inputs always have values)
But I want to get only items, that were checked. How could I change my checkbox-matrix template to solve this problem?
回答1:
Finally I decided to handle this problem in my post-action instead. Removing items (checkboxes) that were not selected, and have nulls
in answerResult[##].SubQuestionId
fields.
来源:https://stackoverflow.com/questions/5391055/asp-net-mvc-checkbox-radiobutton-matrix-model-binding