在http post方法中将响应作为null

时间:2014-02-11 12:40:01

标签: c# asp.net-mvc-4

我使用以下代码:

控制器:

public ActionResult Update(int studentId = 0, int subjectId = 0)
        {
            Engine engine = new Engine(studentId, subjectId);
            List<Chapter> chapterList = engine.GetChapters();

            return View(chapterList);
        }

        [HttpPost]
        public ActionResult Update(List<Chapter> model)      
        {           

            return View(model);
        }

Update.cshtml:

@model IEnumerable<Chapter>
@{
    ViewBag.Title = "Update";
}
<h2>
    Update</h2>
@using (Html.BeginForm("Update", "StudyPlan", FormMethod.Post))
{
    <fieldset>
        <table>
            @foreach (var item in Model)
            {

                <tr>
                    <td>
                        @item.name
                    </td>
                    <td>
                        @Html.CheckBoxFor(chapterItem => item.included)
                    </td>
                </tr>
            }
        </table>
        <input type="submit" value="submit" />
    </fieldset>


}

我希望当用户选中复选框时,响应应该出现在控制器的httppost方法中。但我得到null值更新方法。我做错了吗

2 个答案:

答案 0 :(得分:0)

您需要使用for代替foreach。在这种情况下,复选框将呈现为

<input type='checkbox' name='Model[0].included'/>
<input type='checkbox' name='Model[1].included'/>
...

然后ModelBinder将成功创建模型

示例:

@model List<Chapter>
@{
    ViewBag.Title = "Update";
}
<h2>
    Update</h2>
@using (Html.BeginForm("Update", "StudyPlan", FormMethod.Post))
{
    <fieldset>
        <table>
            @for (int i =0;i<Model.Count;i++)
            {

                <tr>
                    <td>
                        @Model[i].name
                    </td>
                    <td>
                        @Html.CheckBoxFor(chapterItem => Model[i].included)
                    </td>
                </tr>
            }
        </table>
        <input type="submit" value="submit" />
    </fieldset>


}

PS。在该示例中,模型从List<>

更改为IEnumerable

这是因为MVC在CheckBoxFor方法中分析表达式。它的表达式是数组访问器,然后它生成不同的控件名称。并基于Name ModelBinder成功创建List<>

答案 1 :(得分:0)

正如谢尔盖所​​说,使用for循环,但试试这个:

@for (int i =0;i<Model.Count;i++)
{

    <tr>
        <td>
            @Html.HiddenFor(m => m[i].id)
            @Html.DisplayFor(m => m[i].name)
        </td>
        <td>
            @Html.CheckBoxFor(m => m[i].included)
        </td>
    </tr>
}
相关问题