ASP.NET Core中表格多表单批量提交并更新购物车商品数量的实现方法
购物车批量更新数量实现方案
1. 调整视图代码
将整个商品表格包裹在指向批量更新接口的表单内,同时给商品ID隐藏域、数量输入框添加符合ASP.NET Core模型绑定规则的name属性,原有单个商品删除的表单逻辑无需改动。修改后的视图代码如下:
<!-- 新增包裹整个表格的批量更新表单 --> <form asp-action="UpdateCart" asp-controller="Cart" method="post"> <table class="table table-hover"> <thead> <tr> <th></th> <th>Product</th> <th>Price</th> <th class="qtycolumn">Quantity</th> <th>Total</th> <th></th> </tr> </thead> <tbody> @{int index = 0;} @foreach (var item in Model.Products) { <tr> <td><img alt="" class="img-responsive product-thumb" src="images/products/tn/@item.Product.Image"></td> <td><a href="#">@item.Product.ProductName</a></td> <td>@item.Product.Price.ToString("c")</td> <td> <div class="form-group"> <!-- 给隐藏域加name属性,用索引标识不同商品 --> <input type="hidden" name="Products[@index].ProductId" value="@item.Product.ProductID" /> <!-- 给数量输入框加name属性 --> <input type="number" name="Products[@index].Quantity" class="form-control" value="@item.Quantity" min="1" step="1"> </div> </td> <td>@((item.Quantity*item.Product.Price).ToString("c"))</td> <td> <form asp-action="RemoveFromCart" asp-controller="Cart" method="post"> <input type="hidden" name="ProductId" value="@item.Product.ProductID" /> <button type="submit" class="btn btn-danger btn-sm"> <i class="fa fa-times fa-fw"></i> Remove </button> </form> </td> </tr> { index++; } } </tbody> </table> <!-- 新增批量保存按钮 --> <button type="submit" class="btn btn-primary">保存所有商品数量</button> </form>
2. 定义接收参数的视图模型
新增两个视图模型类,用于接收批量提交的商品数据:
// 单个购物车商品的更新参数 public class CartItemUpdateVM { public int ProductId { get; set; } public int Quantity { get; set; } } // 批量更新购物车的整体请求参数 public class CartUpdateVM { public List<CartItemUpdateVM> Products { get; set; } }
3. 编写后端批量更新接口
在CartController中新增UpdateCart处理逻辑,和你现有加购逻辑的购物车操作保持一致即可:
[HttpPost] public IActionResult UpdateCart(CartUpdateVM model) { // 获取当前登录用户ID,替换为你项目中的实际取数逻辑 var currentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier); foreach (var item in model.Products) { // 查询当前用户购物车中的对应商品 var cartItem = _context.CartItems.FirstOrDefault(c => c.ProductId == item.ProductId && c.UserId == currentUserId); if (cartItem != null) { // 更新商品数量 cartItem.Quantity = item.Quantity; } } // 保存修改到数据库 _context.SaveChanges(); // 刷新购物车页面 return RedirectToAction("Index"); }
可选:无刷新提交方案
如果需要避免页面刷新,可以用AJAX提交表单:
// 给批量更新表单绑定提交事件 document.querySelector('form[asp-action="UpdateCart"]').addEventListener('submit', function(e) { e.preventDefault(); fetch(this.action, { method: 'POST', body: new FormData(this), headers: { 'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value } }).then(res => { if (res.ok) location.reload(); }) })
内容的提问来源于stack exchange,提问作者serhatyt
相关产品推荐
相关产品推荐

