public ActionResult Create(Recipe recipe, int[] groups) { try { User currentUser = _recipeContext.Users.Single(u => u.Id.ToUpper() == User.Identity.Name.ToUpper()); recipe.User = currentUser; recipe.PostedOn = DateTime.Now; IQueryable<Group> selectedGroups = _recipeContext.Groups.Where(g => groups.Contains(g.Id)); foreach (Group selectedGroup in selectedGroups) { recipe.Groups.Add(selectedGroup); } currentUser.Recipes.Add(recipe); _recipeContext.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult Edit(Recipe recipe, int[] groups) { Recipe originalRecipe = _recipeContext.Recipes.Single(r => r.Id == recipe.Id); originalRecipe.Name = recipe.Name; originalRecipe.Description = recipe.Description; originalRecipe.Ingredients = recipe.Ingredients; originalRecipe.Directions = recipe.Directions; if (groups == null) { originalRecipe.Groups.Clear(); } else { foreach (Group groupToRemove in originalRecipe.Groups.Where(g => !groups.Contains(g.Id)).ToArray()) { originalRecipe.Groups.Remove(groupToRemove); } } if (groups != null) { foreach (int groupIdToAdd in groups.Where(groupId => !originalRecipe.Groups.Any(g => g.Id == groupId))) { originalRecipe.Groups.Add(_recipeContext.Groups.Single(g => g.Id == groupIdToAdd)); } } _recipeContext.SaveChanges(); return RedirectToAction("Index"); }