MVC3如何在控制器中的类中发布列表?

我上课了:

public class CarList { public int quantity{get;set;} public List Cars {get;set;} } public class Car { public string Name {get;set;} } 

然后我在列表中创建一个包含三辆汽车的汽车列表。 然后我使用for循环Model.Cars在屏幕上显示信息。 当我提交表单时,数量字段具有有效值但Cars为空。

 [HttpPost] public ActionResult Save(CarList list) { //why is list.Cars NULL when i am posting three items in the list } 

查看:Model = Car,添加了一行

为Car添加了新的编辑器模板,其中包含

Name Html.TextBoxFor(x=>Model.Name)

在主视图中:Model = CarList,添加了forloop

 @{foreach (Car item in Model.Cars) { @Html.EditorFor(x=>item); } 

使用EditorTemplate ,你会很好。

创建一个名为“ EditorTemplates ”的文件夹,并创建一个名为Car.cshtml的视图(编辑器模板)

在此处输入图像描述

现在将以下代码添加到此新视图中。

 @model Car 

@Html.TextBoxFor(x => x.Name)

现在在主视图中,使用Html.EditorFor HTML帮助程序方法来调用此编辑器模板

 @model SO_MVC.Models.CarList 

CarList

@using (Html.BeginForm()) {

Quanitty

@Html.TextBoxFor(x => x.quantity) @Html.EditorFor(x=>x.Cars) }

现在有一个HTTPPOst动作方法来接受表单发布

 [HttpPost] public ActionResult CarList(CarList model) { //Check model.Cars property now. } 

您现在将看到结果 在此处输入图像描述

实际上你不需要循环收集汽车。 你只是喜欢它

 @Html.EditorFor(x => x.Cars) 

我认为这是问题所在:

 @foreach (Car item in Model.Cars) { @Html.EditorFor(x=>item); } 

将其更改为

 @foreach (Car item in Model.Cars) { @Html.EditorFor(x=>item.Name); } 

虽然我不记得曾经遇到过这个问题,但是模型绑定器的情况可能不够灵活,无法将多个级别绑定在一起。 它也可能有助于将Glimpse(http://getglimpse.com/)添加到您的项目中,以便您可以查看请求的实际处理方式。