0

当我调试我的 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 得到一个值并被添加。

4

2 回答 2

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" } };
}
于 2012-10-31T10:58:08.687 回答
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" } };
}
于 2012-10-31T11:05:14.343 回答