4

我在 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&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=2 >2&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=3 >3&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=4 >4&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=5 >5&nbsp;&nbsp;</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&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=2 >2&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=3 >3&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=4 >4&nbsp;&nbsp;<input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=5 >5&nbsp;&nbsp;</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");
    }

经过测试,以下是我的观察:

  1. 如果我在每个问题上至少CheckBox选择了一个,那么这可以正常工作并且在我的控制器中updater.questions.Length == 5并且数据完美绑定。

  2. 如果我根本不回答其中一个问题,我只会得到一个与我跳过的数字一样大的数组:-1. 因此,如果我没有回答问题 #3,我会在控制器操作 2 中得到一个数组。

  3. 通过使用#2的逻辑,如果我不回答第一个问题,我只是null得到updater.questions

我想要得到(以及我所期望的)是:

我总是会得到questions一个长度,5并且在我没有回答其中一个问题的情况下,我会简单地0为那个 index 获得一个大小合适的数组responseIds

这是 ASP.NET MVC 模型绑定中的错误吗?如果没有,我是否缺少任何东西或任何方法来获得我正在寻找的所需行为?

4

1 回答 1

5

我认为这个问题是因为当没有选择任何选项时,输入甚至没有在请求参数中传回。解决此问题的一种方法是设置一个默认的隐藏复选框,其中包含一个已知值,您可以为每个问题最初选择该值(如果您愿意,可以选择“未回答”复选框)。这将保证您获得每个问题的选择,并且数组中的每个元素都存在一个请求参数。

从发回的内容的角度考虑它。只有那些具有值、具有名称且未被禁用的元素才会被发布。如果不是所有问题都有值,那么它应该创建多少个数组项?充其量它可以猜测选择的最后一个项目应该是数组的大小——但是对于介于两者之间的任何项目,它应该使用什么值?该框架无法读懂您的想法,并且可以说不应该为该类型提供默认值可能是合理的。IMO,最好省略该值,因此,如果需要,强制开发人员提供默认值。这似乎就是正在发生的事情。

于 2010-01-02T16:05:44.577 回答