You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC购物车Quantity属性修改问题:保存无响应

修正ASP.NET MVC购物车编辑Quantity无响应的问题

问题原因

  1. 请求方法不匹配:表单默认以POST方法提交,但你的Edit方法标记了[HttpPatch],导致路由无法匹配,请求未被处理,所以点击保存无反应。
  2. 多余且错误的UpdateModel调用:UpdateModel(carts)是用于更新单个模型对象的方法,传入List<Cart>属于用法错误,且你已经手动修改了购物车项的Quantity,该调用完全多余。

修正方案

1. 修改Controller的Edit POST方法

将[HttpPatch]改为[HttpPost],简化逻辑并添加防伪验证:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, int quantity)
{
    var carts = GetListCarts();
    var cartItem = carts.Find(s => s.ProductID == id);
    
    if (cartItem != null && quantity > 0)
    {
        cartItem.Quantity = quantity;
        // carts是Session中对象的引用,修改属性后Session会自动同步,无需重新赋值
    }
    
    return RedirectToAction("ListCarts");
}

也可以使用模型绑定实现更简洁的逻辑:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Cart model)
{
    var carts = GetListCarts();
    var cartItem = carts.Find(s => s.ProductID == model.ProductID);
    
    if (cartItem != null && model.Quantity > 0)
    {
        cartItem.Quantity = model.Quantity;
    }
    
    return RedirectToAction("ListCarts");
}

2. (可选)使用PATCH方法的额外配置(不推荐)

如果一定要用PATCH方法,需要修改表单指定请求方法,并引入相关脚本:

@using (Html.BeginForm("Edit", "Cart", FormMethod.Post, new { @data_method = "PATCH" }))

同时需要引入jquery.unobtrusive-ajax.js并配置,但这种方式比直接用POST复杂,优先推荐第一种方案。

关于readonly字段的疑问

View中设置为readonly的字段(ProductID、ProductName、UnitPrice)不会影响更新逻辑:

  • readonly仅在前端禁止用户手动编辑,表单提交时这些字段的原始值仍会被发送到服务器。
  • 你的更新逻辑仅修改Quantity,并未操作这些只读字段,且是从Session中获取购物车项进行修改,即使前端篡改了这些字段的值,也不会影响Session中的数据,安全性有保障。

内容的提问来源于stack exchange,提问作者Sakai Haki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:25:30