public DishIngredientVM EditDishIngredientsInCartGet(int cartItemId, int dishId, HttpContext httpContext) { var cartId = httpContext.Session.GetInt32("Cart"); var newDishVM = new DishIngredientVM(); var ingredients = _context.Ingredients.ToList(); var cartItem = _context.CartItems .Include(x => x.Dish) .Include(i => i.CartItemIngredient) .SingleOrDefault(x => x.CartId == cartId && x.Dish.DishId == dishId && x.CartItemId == cartItemId); var selectedIngredients = new List <SelectedIngredients>(); foreach (var item in ingredients) { var selected = new SelectedIngredients { Name = item.Name, Id = item.IngredientId, Price = item.Price }; if (cartItem.CartItemIngredient.Any(x => x.Ingredient.IngredientId == item.IngredientId)) { selected.Enabled = true; } if (EnabledIngredientIsNull(dishId, item.IngredientId)) { selected.Price = 0; } selectedIngredients.Add(selected); } newDishVM.Dish = cartItem.Dish; newDishVM.SelectedIngredients = selectedIngredients; newDishVM.DishId = cartItem.Dish.DishId; newDishVM.CartItemId = cartItem.CartItemId; return(newDishVM); }
public void EditDishIngredientsInCartPost(DishIngredientVM dishIngredientVM, HttpContext httpContext) { var cartId = httpContext.Session.GetInt32("Cart"); var cartItem = _context.CartItems .Include(x => x.Dish) .Include(i => i.CartItemIngredient) .ThenInclude(s => s.Ingredient) .SingleOrDefault(x => x.CartId == cartId && x.Dish.DishId == dishIngredientVM.DishId && x.CartItemId == dishIngredientVM.CartItemId); var existingIngredients = cartItem.CartItemIngredient.Select(x => x.IngredientId).ToList(); var SelectedIds = dishIngredientVM.SelectedIngredients.Where(x => x.Enabled == true).Select(s => s.Id).ToList(); var unCheckedIds = dishIngredientVM.SelectedIngredients.Where(x => x.Enabled == false).Select(s => s.Id).ToList(); var ingredientsToAdd = _context.Ingredients.Where(x => SelectedIds.Contains(x.IngredientId)).ToList(); var ingredientsToRemove = _context.Ingredients.Where(x => unCheckedIds.Contains(x.IngredientId)).ToList(); cartItem.CartItemIngredient.ForEach(i => _context.Remove(i)); _context.SaveChangesAsync(); foreach (var item in ingredientsToAdd) { var newIngredient = new CartItemIngredient { CartItem = cartItem, Ingredient = item, CartItemId = cartItem.CartItemId, IngredientId = item.IngredientId, CartItemIngredientPrice = item.Price }; cartItem.CartItemIngredient.Add(newIngredient); } _context.SaveChangesAsync(); }
public IActionResult EditDishIngredientsInCart(DishIngredientVM dishIngredientVM) { _cartService.EditDishIngredientsInCartPost(dishIngredientVM, HttpContext); return(RedirectToAction("Index", "Dish")); }
public IActionResult EditDishIngredientsInCheckout(DishIngredientVM dishIngredientVM) { _cartService.EditDishIngredientsInCartPost(dishIngredientVM, HttpContext); return(RedirectToAction("Checkout", "Payment")); }