我在 ASP.NET MVC 中有一个简单的表单。我正在尝试将这些结果发布到控制器操作中,但我遇到了奇怪的行为。
这view
是一个简单的 HTML 表格:
这是 HTML 表单视图的一部分:
<form action="/Applications/UpdateSurvey" method="post"><table id=questionsTable class=questionsTable border=1>
<thead><tr><td>Name</td><td>Answer</td><td>Name Attribute(for debugging)</td></tr> </thead><tbody>
<tr>
<td>Question 0:</td>
<td><input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=1 >1 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=2 >2 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=3 >3 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=4 >4 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=5 >5 </td>
<td>updater.questions[0].responseIds</td>
</tr>
<tr>
<td>Question 1:</td>
<td><input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=1 >1 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=2 >2 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=3 >3 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=4 >4 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=5 >5 </td>
<td>updater.questions[1].responseIds</td>
</tr>
</tbody></table>
<input type="submit" value="Save" />
</form>
绑定对象:
public class SurveyUpdater
{
public Question[] questions { get; set; }
}
public class Question
{
public int[] responseIds { get; set; }
}
控制器动作代码:
public ActionResult UpdateSurvey(SurveyUpdater updater)
{
if (updater.questions == null)
{
//I dont understand why this is getting hit
}
if (updater.questions.Length != 5)
{
//I dont understand why this is getting hit
}
return View("TestSurvey");
}
经过测试,以下是我的观察:
如果我在每个问题上至少
CheckBox
选择了一个,那么这可以正常工作并且在我的控制器中updater.questions.Length == 5
并且数据完美绑定。如果我根本不回答其中一个问题,我只会得到一个与我跳过的数字一样大的数组:
-1
. 因此,如果我没有回答问题 #3,我会在控制器操作 2 中得到一个数组。通过使用#2的逻辑,如果我不回答第一个问题,我只是
null
得到updater.questions
我想要得到(以及我所期望的)是:
我总是会得到questions
一个长度,5
并且在我没有回答其中一个问题的情况下,我会简单地0
为那个 index 获得一个大小合适的数组responseIds
。
这是 ASP.NET MVC 模型绑定中的错误吗?如果没有,我是否缺少任何东西或任何方法来获得我正在寻找的所需行为?