Пример #1
0
        public IActionResult Buy(int id)
        {
            ProductModel productModel = new ProductModel();

            if (SessionsHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart") == null)
            {
                List <Item> cart = new List <Item>();
                cart.Add(new Item {
                    Product = productModel.find(id), Quantity = 1
                });
                SessionsHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            else
            {
                List <Item> cart  = SessionsHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart");
                int         index = isExist(id);
                if (index != -1)
                {
                    cart[index].Quantity++;
                }
                else
                {
                    cart.Add(new Item {
                        Product = productModel.find(id), Quantity = 1
                    });
                }
                SessionsHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            return(RedirectToAction("Index"));
        }
Пример #2
0
        public IActionResult Index()
        {
            var cart = SessionsHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart");

            ViewBag.cart  = cart;
            ViewBag.total = cart.Sum(item => item.Product.Price * item.Quantity);
            return(View());
        }
Пример #3
0
        public IActionResult Remove(int id)
        {
            List <Item> cart  = SessionsHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart");
            int         index = isExist(id);

            cart.RemoveAt(index);
            SessionsHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            return(RedirectToAction("Index"));
        }
Пример #4
0
        private int isExist(int id)
        {
            List <Item> cart = SessionsHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart");

            for (int i = 0; i < cart.Count; i++)
            {
                if (cart[i].Product.Id.Equals(id))
                {
                    return(i);
                }
            }
            return(-1);
        }