发布后返回null模型

时间:2018-03-08 18:56:17

标签: c# asp.net asp.net-mvc razor model-binding

似乎很多人都有这个问题,但我还没有找到解决方案。

我首先将门票发送到我的视图

[HttpGet]
    public ActionResult AddPopcorn()
    {
        List<Ticket> tickets = new List<Ticket>();
        // Fill the list with tickets
        return View("AddPopcorn", tickets);
    }

在视图中,我使用表单和复选框显示票证。视图正确显示票证。

@model List<Domain.Entities.Ticket>

@{
    ViewBag.Title = "AddPopcorn";
}

<body>
  // Html stuff
        @using (Html.BeginForm("AddPopcorn", "Ticket", FormMethod.Post))
        {
            <table>
                @foreach (var item in Model)
                {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.TicketID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Price)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.TicketType)
                    </td>
                    <td>
                        @Html.CheckBoxFor(modelItem => item.Popcorn)
                    </td>
                </tr>
                }
            </table>
            <input type="submit" value="Voeg toe!" />
        }
    </div>
</body>

如果有人选中复选框,我想要价值&#39;爆米花&#39;是真实的。因此,我希望视图根据复选框返回包含爆米花更新值的故障单列表。

    [HttpPost]
    public ActionResult AddPopcorn(List<Ticket> model)
    {
        foreach (var item in model)
        {
            if (item.Popcorn == true)
            {
                item.Price = item.Price + 5;
            }
        }
        return RedirectToAction("Payment", "Payment");
    }

但是,返回到AddPopcorn的模型为null。我似乎无法弄明白为什么。

2 个答案:

答案 0 :(得分:1)

尝试将foreach循环更改为for

for (int i = 0; i < Model.Count; i++)
{
  <tr>
    <td>
      @Html.DisplayFor(x => Model[i].TicketID)
    </td>

    <td>
      @Html.DisplayFor(x => Model[i].Price)
    </td>

    // etc 

    <td>
      @Html.CheckBoxFor(x => Model[i].Popcorn)
    </td>        
  </tr>   
}

默认模型绑定器使用特定约定来计算如何绑定项列表,例如Model[0].Popcorn(名称)。您可以检查CheckBox的HTML是否将name属性设置为该格式。

除了使用for之外,您还可以为EditorTemplate对象指定自定义Ticket

答案 1 :(得分:0)

这是因为您的表单实际上并未将任何数据发回给控制器。

您需要输入元素才能真正从表单中检索数据。

相反,在控制器上,以这种方式访问​​模型:

var model = this.Model

表单将发送您在输入标记中获得的数据,例如

<input type="text" name="first_name" />
相关问题