Ejemplo n.º 1
0
        public async Task <IActionResult> AddBasket(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            Product product = await _db.Products.FindAsync(id);

            if (product == null)
            {
                return(NotFound());
            }
            List <BasketProductVM> products;

            if (Request.Cookies["basket"] == null)
            {
                products = new List <BasketProductVM>();
            }
            else
            {
                products = JsonConvert.DeserializeObject <List <BasketProductVM> >(Request.Cookies["basket"]);
            }
            BasketProductVM checkProduct = products.FirstOrDefault(p => p.Id == id);

            if (checkProduct == null)
            {
                BasketProductVM basketProductVM = new BasketProductVM()
                {
                    Id    = product.Id,
                    Image = product.Image,
                    Price = product.Price,
                    Title = product.Title,
                    Count = 1
                };
                products.Add(basketProductVM);
            }
            else
            {
                checkProduct.Count++;
            }
            string basket = JsonConvert.SerializeObject(products);

            Response.Cookies.Append("basket", basket, new CookieOptions {
                MaxAge = TimeSpan.FromDays(15)
            });
            return(RedirectToAction(nameof(Index)));
        }
Ejemplo n.º 2
0
        public IActionResult Remove(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            List <BasketProductVM> basketProducts = JsonConvert.DeserializeObject <List <BasketProductVM> >(Request.Cookies["basket"]);
            BasketProductVM        findIdProduct  = basketProducts.FirstOrDefault(p => p.Id == id);

            if (findIdProduct.Count == 1)
            {
                basketProducts.Remove(findIdProduct);
            }
            else
            {
                findIdProduct.Count--;
            }
            string removeProduct = JsonConvert.SerializeObject(basketProducts);

            Response.Cookies.Append("basket", removeProduct, new CookieOptions {
                MaxAge = TimeSpan.FromDays(15)
            });
            return(RedirectToAction(nameof(Basket)));
        }