首先,在视图层面,将所需商品数量渲染成表单:
@foreach(var item in Model)
{
@item.Name
@item.Price
@Html.BeginForm("UpdateCart", "Cart", new { id = item.Id })
{
}
@Html.ActionLink("Remove", "RemoveFromCart", "Cart", new { id = item.Id }, null)
}
这里利用了HTML辅助器Html.BeginForm()
来创建表单,并设置了name
属性为"quantity",表明输入框里的数值是商品的数量,而在value
属性中则填入了商品当前的数量。
然后,在控制器层面,编写更新购物车商品数量的方法:
[HttpPost]
public ActionResult UpdateCart(int id, int quantity)
{
var item = db.Cart.SingleOrDefault(i => i.Id == id);
if (item != null)
{
item.Quantity = quantity;
db.SaveChanges();
}
return RedirectToAction("Index");
}
该方法标有[HttpPost]
特性,表示只能接收POST请求,以防止意外的请求。该方法接收id
和quantity
两个参数,其中id
是指当前商品的ID,quantity
是指已更新的商品数量。接下来,该方法通过SingleOrDefault()
方法从数据库中查找到该商品的实例,如果存在的话,则将其数量更新为新的数量,并且通过db.SaveChanges()
方法将更改保存到数据库中。最后,返回到购物车的索引页面并刷新。
这样,当用户在结账时更改购物车中商品的数量,这个数量就会在购物车