【问题标题】:Getting response as null in http post method在http post方法中获取响应为null
【发布时间】:2014-02-11 12:40:00
【问题描述】:

我正在使用以下代码:

控制器:

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);
        }

更新.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 方法。但我得到空值更新方法。我是不是做错了什么

【问题讨论】:

  • 你的chapter 模型是什么样的?

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


【解决方案1】:

您需要使用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。在该示例中,模型从 IEnumerable 更改为 List&lt;&gt;

这是因为 MVC 分析 CheckBoxFor 方法中的表达式。如果这个表达式是数组访问器,那么它会生成不同的控件名称。并基于Name ModelBinder成功创建List&lt;&gt;

【讨论】:

  • 现在,nameid 属性为空,如何解决?
  • 它们以 null 的形式出现,因为它们没有任何 Input 元素。如果要在模型中接收它们,则需要添加它们。您可以将它们添加为Html.HiddenFor(m =&gt; Model[i].id)Html.HiddenFor(m =&gt; Model[i].name)。 MVC 根据页面上的 input\textarea 字段创建模型对象。
【解决方案2】:

按照 Sergey 的建议,使用 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>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多