示例#1
0
        public IActionResult AddToCart(int productId)
        {
            int cartCount;

            try
            {
                // if user is not logged in, update cart data in Session State as
                // a Jsonified CartList object
                if (!User.Identity.IsAuthenticated)
                {
                    var cartList = HttpContext.Session.GetJson <CartListViewModel>("cart");

                    // check if "cart" exists in Session data
                    if (cartList != null)
                    {
                        cartList.AddToCart(new Cart {
                            ProductId = productId, Qty = 1
                        });
                    }
                    // create new new CartList object if there isn't one in session
                    else
                    {
                        cartList = new CartListViewModel();
                        cartList.AddToCart(new Cart {
                            ProductId = productId, Qty = 1
                        });
                    }

                    // update "cart" Session data
                    HttpContext.Session.SetJson("cart", cartList);
                    // get latest "cartCount"
                    cartCount = cartList.CartCount;

                    // for debugging, to delete
                    //foreach (Cart c in cartList.List)
                    //{
                    //    Debug.WriteLine($"Prod: {c.ProductId} - {c.Qty}");
                    //}
                    //Debug.WriteLine("Cart count: " + cartCount);
                }
                // else user is logged in, update cart data in SQL db Cart table
                else
                {
                    string userId = User.FindFirst("userId").Value;
                    var    cart   = db.Carts.FirstOrDefault(c => c.ProductId == productId && c.UserId == userId);

                    // check if cart item for this product exists
                    if (cart != null)
                    {
                        cart.Qty += 1;
                    }
                    // create new Cart object if cart item doesnt exist
                    else
                    {
                        cart = new Cart()
                        {
                            UserId = userId, ProductId = productId, Qty = 1
                        };
                        db.Carts.Add(cart);
                    }
                    db.SaveChanges();

                    // get latest "cartCount"
                    cartCount = db.Users.FirstOrDefault(u => u.Id == userId).Carts.Sum(c => c.Qty);

                    // for debugging, to delete
                    //foreach (var c in db.Users.FirstOrDefault(u => u.Id == userId).Carts)
                    //{
                    //    Debug.WriteLine($"Prod: {c.ProductId} - {c.Qty}");
                    //}
                    //Debug.WriteLine("Cart count: " + cartCount);
                }

                HttpContext.Session.SetInt32("cartCount", cartCount);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                _logger.LogError(ex, $"Error adding to cart for prod Id {productId}");

                return(Json(new
                {
                    success = false
                }));
            }
            return(Json(new { success = true, cartCount = cartCount }));
        }