当我调试我的actionresult AddToCart时。我的购物车获得了一个productId的值,它在这里工作得很好:
public ActionResult AddToCart(int productID)
{
List<int> cart = (List<int>)Session["cart"];
if (cart == null){
cart = new List<int>();
}
cart.Add(productID);
return new JsonResult() { Data = new { Status = "Success" } };
}
我正在使用ajax来获取productID:
$(function () {
$(".a").live("click", function () {
var $this = $(this),
productID = $this.data('productID');
$.ajax({
url: '/Home/AddToCart',
type: "post",
cache: false,
data: { productID: productID },
success: function (data) {
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
});
但是当我实现这个actionresult时,我的购物车是空的:
public ActionResult ShoppingCart()
{
var cart = Session["cart"] as List<int>;
var products = cart != null ? cart.Select(id =>
{
var product = repository.GetProductById(id);
return new ProductsViewModel
{
Name = product.Name,
Description = product.Description,
price = product.Price
}
}) : new List<ProductsViewModel>();
return PartialView(products);
}
我做错了什么?为什么actionresult Shoppingcart有空值这是怎么发生的?当我调试AddToCart时,Cart获取一个值并添加它。
答案 0 :(得分:2)
您应该在向其添加项目后更新会话内的购物车对象:
public ActionResult AddToCart(int productID)
{
List<int> cart = (List<int>)Session["cart"];
if (cart == null){
cart = new List<int>();
}
cart.Add(productID);
Session["cart"] = cart;
return new JsonResult() { Data = new { Status = "Success" } };
}
答案 1 :(得分:1)
您也需要更新会话购物车,例如......
public ActionResult AddToCart(int productID)
{
List<int> cart = (List<int>)Session["cart"];
if (cart == null){
Session["cart"] = cart = new List<int>();
}
cart.Add(productID);
return new JsonResult() { Data = new { Status = "Success" } };
}