See my solution below:
Controller / Models
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CartSample.Controllers
{
public class CartController : Controller
{
[HttpGet]
public ActionResult Index()
{
var model = new Order
{
Products = new List<Product>
{
new Product
{
Name = "item 1",
Qty = 2,
Price = 9.99m
}
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(Order model)
{
foreach(var product in model.Products)
{
UpdateProductQty(product);
}
return View(model);
}
private void UpdateProductQty(Product product)
{
var updatedQuantity = product.Qty;
}
}
public class Order
{
public List<Product> Products { get; set; }
public Order()
{
Products = new List<Product>();
}
}
public class Product
{
public string Name { get; set; }
public int Qty { get; set; }
public decimal Price { get; set; }
public decimal Total()
{
return Price * Qty;
}
}
}
View
Note: how I have used Html.hiddenFor to ensure the built in MVC mechanism maps the form fields for existing cart items to the model parameter for the Index (post) action in the controller.
That way you can easily look in the model submitted to action post and do what you want with updated Qty for every item.
@model CartSample.Controllers.Order
<html>
<head><title>Cart Sample</title>
</head>
<body>
@using (Html.BeginForm("Index", "Cart", FormMethod.Post))
{
<table>
<tr>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
</tr>
@for (int i = 0; i < Model.Products.Count; i++)
{
<tr>
<td>@Html.HiddenFor(x=>x.Products[i].Name)
@Html.DisplayFor(x=>x.Products[i].Name)</td>
<td>@Html.TextBoxFor(x=>x.Products[i].Qty)</td>
<td>@Html.HiddenFor(x => x.Products[i].Price)
@Html.DisplayFor(x => x.Products[i].Price)</td>
<td>@Model.Products[i].Total()</td>
</tr>
}
<tr>
<td>
<input type="submit" value="update" />
</td>
</tr>
</table>
}
</body>
</html>
This results in the following screens
https://s9.postimg.org/puc32qwdr/Cart.png[
^]