I have a view model that contains a Product class type and an IEnumerable< Product > type. On the post the first level product object comes back binded from the viewmode
You are not using your lambda expression properly. You need to be accessing the Products list through the model. Try doing it like this:
@count = 0
foreach (var item in Model.Products)
{
@Html.LabelFor(model => model.Products[count].ID)
@Html.EditorFor(model => model.Products[count].ID)
@Html.LabelFor(model => model.Products[count].Name)
@Html.EditorFor(model => model.Products[count].Name)
@Html.LabelFor(model => model.Products[count].Price)
@Html.EditorFor(model => model.Products[count].Price)
@count++
}
Edit
Controller:
BoringStoreContext db = new BoringStoreContext();
public ActionResult Index()
{
ProductIndexViewModel viewModel = new ProductIndexViewModel
{
NewProduct = new Product(),
Products = db.Products
};
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ProductIndexViewModel viewModel)
{
// work with view model
return View();
}
Model
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductIndexViewModel
{
public Product NewProduct { get; set; }
public List Products { get; set; }
}
public class BoringStoreContext
{
public BoringStoreContext()
{
Products = new List();
Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) });
Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) });
}
public List Products { get; set; }
}
View:
@model Models.ProductIndexViewModel
@using (@Html.BeginForm())
{
@Html.LabelFor(model => model.NewProduct.Name)
@Html.EditorFor(model => model.NewProduct.Name)
@Html.LabelFor(model => model.NewProduct.Price)
@Html.EditorFor(model => model.NewProduct.Price)
for (int count = 0; count < Model.Products.Count; count++ )
{
@Html.LabelFor(model => model.Products[count].ID)
@Html.EditorFor(model => model.Products[count].ID)
@Html.LabelFor(model => model.Products[count].Name)
@Html.EditorFor(model => model.Products[count].Name)
@Html.LabelFor(model => model.Products[count].Price)
@Html.EditorFor(model => model.Products[count].Price)
}
}