这是我用于购物车的两个动作结果:
我通过使用ajax将 第二个动作我将它填充到我的模型中,以便我可以在我看来使用它: 现在我有一个在购物车视图中显示产品的视图。 显示的每个产品都有一个显示“删除”的按钮 我的问题是如何以最佳方式从会话购物车中删除产品? Actionresult应该如何? 我创建了一个Ajax脚本来获取当有人点击删除按钮时需要删除的产品的ID: 如果我认为使用javascript,如果我想通过我收到的ID删除产品,那么actionresult应该如何? 我猜应该看起来像这样: 如果我仍然认为正确,我应该如何在 感谢任何形式的帮助。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);
}
$(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>");
}
});
});
});
public ActionResult DeleteProductFromCart(int ProductImageId)
{
// code..
}
DeleteProductFromCart
上的括号内编码?
答案 0 :(得分:2)
我认为它应该与添加非常相似。 我添加了一个额外的检查,因为尝试从不存在的购物车中删除某些东西是不合逻辑的
public ActionResult DeleteProductFromCart(int ProductImageId)
{
List<int> cart = (List<int>)Session["cart"];
if (cart == null)
{
return new JsonResult() { Data = new { Status = "ERROR" } };
}
cart.Remove(ProductImageId);
return new JsonResult() { Data = new { Status = "Success" } };
}
答案 1 :(得分:1)
public ActionResult DeleteProductFromCart(int ProductImageId)
{
var cart = Session["cart"] as List<int>;
cart.Remove(ProductImageId);
... return result
}