Exemple #1
0
 public void Post([FromBody] CartView model)
 {
     if (model != null)
     {
         cbl.AddToCart(model);
     }
 }
        public ActionResult AddToCart(int id)
        {
            // Init CartVM list
            List <CartViewModel> cart = Session["cart"] as List <CartViewModel> ?? new List <CartViewModel>();

            // Init CartVM

            Product product = cartBL.AddToCart(id);

            // Check if the product is already in cart
            var productInCart = cart.FirstOrDefault(x => x.ProductId == id);

            try
            {
                // If not, add new
                if (product == null)
                {
                    cart.Add(new CartViewModel()
                    {
                        ProductId   = product.Id,
                        ProductName = product.Name,
                        Quantity    = 1,
                        Price       = product.Price,
                        Image       = product.ImageName
                    });
                }
                else
                {
                    // If it is, increment
                    productInCart.Quantity++;
                }


                // Get total qty and price and add to model

                int     quantity = 0;
                decimal price    = 0m;

                foreach (var item in cart)
                {
                    quantity += item.Quantity;
                    price    += item.Quantity * item.Price;
                }

                model.Quantity = quantity;
                model.Price    = price;

                // Save cart back to session
                Session["cart"] = cart;
            }
            catch (Exception exception)
            {
                log.Error(exception.Message);
            }
            // Return partial view with model
            return(PartialView(model));
        }