leo*_*ora 4 .net c# asp.net-mvc model-binding
我在ASP.NET MVC中有一个简单的表单.我试图将这些结果发布到控制器动作,我的行为很奇怪.
这view是一个简单的HTML表:
图片查看http://img502.imageshack.us/img502/7271/survey.png
以下是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>
Run Code Online (Sandbox Code Playgroud)
绑定对象:
public class SurveyUpdater
{
public Question[] questions { get; set; }
}
public class Question
{
public int[] responseIds { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器动作代码:
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");
}
Run Code Online (Sandbox Code Playgroud)
经过测试,以下是我的观察:
如果我CheckBox在每个问题上至少选择了一个,那么这个工作正常,并且在我的控制器中updater.questions.Length == 5,数据完全绑定.
如果我根本不回答其中一个问题,我只得到一个与我跳过的数字一样大的数组:-1.所以,如果我没有回答问题#3,我的控制器动作为2得到一个数组.
通过使用#2的逻辑,如果我不回答第一个问题,我只是得到null了updater.questions
我想得到的(以及我所期望的)是:
我总是得到questions一个长度,5在我没有回答其中一个问题的情况下,我只0需要为该索引获得一个大小的数组responseIds.
这是ASP.NET MVC模型绑定中的错误吗?如果没有,我有什么遗漏或任何方式来获得我想要的行为吗?
我认为这个问题是因为当没有选择选择时,输入甚至不会在请求参数中传回.解决这个问题的一种方法是使用一个默认的隐藏复选框,其中包含一个已知值,您可以根据每个问题初步选择一个已知值(如果您愿意,则选择"未应答"复选框).这将保证您获得每个问题的选择,并且数组中的每个元素都存在请求参数.
从发布回来的角度考虑一下.仅发布具有值,具有名称且未禁用的元素.如果不是所有问题都有值,那么它应该创建多少个数组项?最多可以猜测所选的最后一项应该是数组的大小 - 但是它应该用于中间任何项目的值是多少?框架无法读懂您的想法,并且可以说,不应该提供该类型的默认值可能是合理的.IMO,最好省略该值,因此,如果需要,强制开发人员提供默认值.这似乎正在发生的事情.
| 归档时间: |
|
| 查看次数: |
429 次 |
| 最近记录: |