【发布时间】:2025-12-09 09:15:02
【问题描述】:
这是我用于购物车的两个操作结果:
我使用 ajax 将 productids 添加到我的会话购物车的第一个操作:
public ActionResult AddToCart(int ProductImageId)
{
List<int> cart = (List<int>)Session["cart"];
if (cart == null)
{
cart = new List<int>();
}
cart.Add(ProductImageId);
Session["cart"] = cart;
return new JsonResult() { Data = new { Status = "Success" } };
}
我将第二个动作填充到我的模型中,以便在我的视图中使用它:
public ActionResult ShoppingCart()
{
var cart = Session["cart"] as List<int>;
var products = cart != null ? cart.Select(id =>
{
var productImage = repository.GetProductByID(id);
return new ProductsViewModel
{
Name = productImage.Products.Name,
Description = productImage.Products.Description.Substring(0, productImage.Products.Description.IndexOf(".") + 1),
price = productImage.Products.Price,
ProductId = productImage.Products.Id,
Image = productImage.ImageUrl,
ProductImageId = productImage.Id
};
}) : new List<ProductsViewModel>();
return View(products);
}
现在我有一个在购物车视图中显示产品的视图。
显示的每个产品都有一个“删除”按钮
我的问题是如何以最佳方式从会话购物车中删除产品?
Actionresult 应该是什么样子?
我创建了一个 Ajax 脚本来获取当有人点击删除按钮时需要删除的产品的 ID:
$(function () {
$(".a").live("click", function () {
var $this = $(this),
ProductImageId = $this.data('ProductImageId');
$.ajax({
url: '/Home/Action', // <- I have not created a actionresult yet
type: "post",
cache: false,
data: { ProductImageId: ProductImageId },
success: function (data) {
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
});
如果我对 javascript 的想法是正确的,如果我想通过我收到的 ID 删除产品,actionresult 应该是什么样的?
我猜它应该是这样的:
public ActionResult DeleteProductFromCart(int ProductImageId)
{
// code..
}
如果我的想法仍然正确,我应该如何在 DeleteProductFromCart 的括号内编码?
感谢任何形式的帮助。
【问题讨论】:
标签: c# javascript ajax asp.net-mvc asp.net-mvc-3