예제 #1
0
        public IActionResult Buy(string id)
        {
            ProductModel productModel = new ProductModel();

            if (SessionHelpers.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart") == null)
            {
                List <Item> cart = new List <Item>();
                cart.Add(new Item {
                    Product = productModel.find(id), Quantity = 1
                });
                SessionHelpers.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            else
            {
                List <Item> cart  = SessionHelpers.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
                    });
                }
                SessionHelpers.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            return(RedirectToAction("Index"));
        }
예제 #2
0
        public IActionResult Index()
        {
            var cart = SessionHelpers.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(string id)
        {
            List <Item> cart  = SessionHelpers.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart");
            int         index = isExist(id);

            cart.RemoveAt(index);
            SessionHelpers.SetObjectAsJson(HttpContext.Session, "cart", cart);
            return(RedirectToAction("Index"));
        }
예제 #4
0
        private int isExist(string id)
        {
            List <Item> cart = SessionHelpers.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);
        }