I have a class:
public class CarList
{
public int quantity{get;set;}
public List Cars {get;set;}
}
public class Car {
public string Name
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.
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
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
Actually you don't need to loop through the cars collection. You just have it like
@Html.EditorFor(x => x.Cars)