/// <summary> /// Takes in the id for a recipe and converts it into the AddEditRecipeViewModel type for displaying /// </summary> /// <param name="recipeId"></param> /// <returns>the edit form view with data already filled in to the form</returns> public IActionResult Edit(int recipeId) { // TODO: get recipes a different way than to assume there is an ingredient //Get the recipe that is assoitated with the id IList<Ingredient> editIngredients = context.Ingredients.Include(p => p.Recipe).Where(p => p.RecipeID == recipeId).ToList(); //Create a AddEditRecipeViewModel AddEditRecipeViewModel editRecipe = AddEditRecipeViewModel.ConvertToViewModel(editIngredients); //pass that into the view return View(editRecipe); }
public IActionResult Edit(AddEditRecipeViewModel addEditRecipeViewModel) { //Check if edit was successful if (ModelState.IsValid) { //Converts the ViewModel into a recipe object var editRecipe = AddEditRecipeViewModel.CreateRecipe(addEditRecipeViewModel); context.Recipes.Update(editRecipe); //Check ingredients //get the old ingredient list to compare IList<Ingredient> prevIngredients = context.Ingredients.Include(p => p.Recipe).Where(p => p.RecipeID == editRecipe.ID).ToList(); //Go through each ingredients from before it was edited foreach (var ingredient in prevIngredients) { //Two Case //edited this ingredient if (addEditRecipeViewModel.IngredientsID.Contains(ingredient.ID)){ int index = addEditRecipeViewModel.IngredientsID.IndexOf(ingredient.ID); ingredient.Name = addEditRecipeViewModel.IngredientsName[index]; context.Update(ingredient); } //deleted this ingredient else { context.Remove(ingredient); } } //If added to the ingredient list with the JS, I will be under NewIngredientsName IList if (addEditRecipeViewModel.NewIngredientsName != null) { foreach (var ingredient in addEditRecipeViewModel.NewIngredientsName) { //Created a new ingredient var newIngredient = AddEditRecipeViewModel.CreateIngredient(ingredient, editRecipe.ID); context.Ingredients.Add(newIngredient); } } context.SaveChanges(); return Redirect("/"); } //reposted the form it there was errors return View(addEditRecipeViewModel); }
public IActionResult Add(AddEditRecipeViewModel addEditRecipeViewModel) { if (ModelState.IsValid) { //Make recipe var newRecipe = AddEditRecipeViewModel.CreateRecipe(addEditRecipeViewModel); context.Recipes.Add(newRecipe); context.SaveChanges(); //Make Ingredients foreach (var ingredientName in addEditRecipeViewModel.NewIngredientsName) { var newIngredient = AddEditRecipeViewModel.CreateIngredient(ingredientName, newRecipe.ID); context.Ingredients.Add(newIngredient); } context.SaveChanges(); return Redirect("/"); } return View(addEditRecipeViewModel); }
//Add a Recipe to your list public IActionResult Add() { AddEditRecipeViewModel addEditRecipeViewModel = new AddEditRecipeViewModel(); return View(addEditRecipeViewModel); }