MVC3 how to post a list within a class in controller?

后端 未结 3 2012
傲寒
傲寒 2021-01-27 03:42

I have a class:

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

public class Car {
    public string Name          


        
相关标签:
3条回答
  • 2021-01-27 04:17

    I think this is the issue:

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

    Change it to

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

    It might a case of the model binder not being smart enough to bind more than one level down, although I don't remember ever having that issue. it may also help to add Glimpse (http://getglimpse.com/) to your project so that you can see how the request is actually processed.

    0 讨论(0)
  • 2021-01-27 04:38

    Use an EditorTemplate and you will be good.

    Create a Folder Called "EditorTemplates" and create a view (the editor template) with the name Car.cshtml

    enter image description here

    Now Add the below code to this new view.

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

    Now in your Main View, Use the Html.EditorFor HTML helper method to call this editor template

    @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" />
    }
    

    Now have an HTTPPOst action method to accept the form posting

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

    You will see the results now enter image description here

    0 讨论(0)
  • 2021-01-27 04:39

    Actually you don't need to loop through the cars collection. You just have it like

    @Html.EditorFor(x => x.Cars)
    
    0 讨论(0)
提交回复
热议问题