【问题标题】:MVC3 how to post a list within a class in controller?MVC3 如何在控制器的类中发布列表?
【发布时间】:2012-05-15 22:37:55
【问题描述】:

我有一堂课:

public class CarList
{
    public int quantity{get;set;}
    public List<Car> 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,添加一行

为带有&lt;tr&gt;&lt;td&gt;Name&lt;/td&gt;&lt;td&gt;Html.TextBoxFor(x=&gt;Model.Name)&lt;/td&gt;&lt;/tr&gt;的汽车添加了新的编辑器模板

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

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

【问题讨论】:

  • 控制器中的模型绑定如何?换句话说,方法签名是什么样的?
  • 还有助于了解您如何将输入绑定到视图本身。
  • 对不起,我看过去了。你已经发布了。我真正需要看到的是你的观点。
  • 它实际上有助于更多地从您的视图中显示实际的标记和代码,而不是点点滴滴。
  • 所以从上面指出的代码中,您没有发现任何问题吗?因为 rest 只是一些
    s 和 html.beginform 等

标签: c# jquery asp.net-mvc-3


【解决方案1】:

实际上,您不需要遍历汽车集合。你就拥有它吧

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

【讨论】:

    【解决方案2】:

    使用 EditorTemplate 你会很好。

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

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

    @model Car
    <p>
       @Html.TextBoxFor(x => x.Name)
    </p>
    

    现在在您的主视图中,使用 Html.EditorFor HTML 辅助方法调用此编辑器模板

    @model SO_MVC.Models.CarList
    <h2>CarList</h2>
    @using (Html.BeginForm())
    {
        <p>Quanitty </p>
        @Html.TextBoxFor(x => x.quantity) 
        @Html.EditorFor(x=>x.Cars)
        <input type="submit" value="Save" />
    }
    

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

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

    您现在将看到结果

    【讨论】:

      【解决方案3】:

      我认为这是问题所在:

      @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/) 添加到您的项目中也可能会有所帮助,这样您就可以查看请求的实际处理方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 2012-03-25
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多