public IActionResult AddToCart(int productId) { // Get the cart from the current session var cart = SessionHelper.GetObjectFromJson <List <ShoppingCartItem> >(HttpContext.Session, "cart"); var product = _repository.GetProductById(productId); if (product == null) { return(NotFound("The product with the given id does not exist")); } // Create a new cart if it doesn't exist if (cart == null) { cart = new List <ShoppingCartItem>(); } int productIndexInCart = ExistsInCart(cart, productId); if (productIndexInCart != -1) { cart[productIndexInCart].Quantity++; } else { // Add to cart cart.Add(new ShoppingCartItem { Product = product, Quantity = 1 }); } SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart); return(RedirectToAction("Shop", "App")); }
public IActionResult RemoveProduct(int productId) { var product = _repository.GetProductById(productId); if (product == null) { return(NotFound("Cannot find the specified product.")); } _repository.RemoveEntity(product); if (_repository.SaveChanges()) { return(RedirectToAction("AdminPage", "AdminPage")); } return(BadRequest("Cannot save the changes to the database.")); }