public ActionResult Edit(int id, EditTeamVM model) { if (ModelState.IsValid) { var team = db.Teams.Find(id); team.Name = model.Name; team.InstitutionID = model.InstitutionID; //remove previous categories List<Category> prevCats = team.Categories.ToList(); foreach (var cat in prevCats) { team.Categories.Remove(cat); } var selectedCategories = new List<Category>(); foreach (var category in model.Categories) { if (category.isChecked) { selectedCategories.Add(db.Categories.Where(c => c.ID == category.CategoryID).First()); } } team.Categories = selectedCategories; var user = usermanager.FindById(team.ApplicationUserID); user.UserName = model.Email; if (model.Password != null) { usermanager.RemovePassword(user.Id); usermanager.AddPassword(user.Id, model.Password); } db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.InstitutionID = new SelectList(db.Institutions, "ID", "Name", model.InstitutionID); var categoriesForVM = new List<EditTeamVM.Category>(); foreach (var category in db.Categories) { var cat = new EditTeamVM.Category() { CategoryID = category.ID, CategoryName = category.Name, isChecked = false }; categoriesForVM.Add(cat); } foreach (var VMcategory in model.Categories) { if (VMcategory.isChecked) { categoriesForVM.First(c => c.CategoryID == VMcategory.CategoryID).isChecked = true; } } model.Categories = categoriesForVM; return View(model); }
public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Team team = db.Teams.Find(id); if (team == null) { return HttpNotFound(); } ViewBag.InstitutionID = new SelectList(db.Institutions, "ID", "Name", team.InstitutionID); var viewmodel = new EditTeamVM(); viewmodel.Categories = new List<EditTeamVM.Category>(); foreach (var category in db.Categories) { var cat = new EditTeamVM.Category() { CategoryID = category.ID, CategoryName = category.Name, isChecked = false}; viewmodel.Categories.Add(cat); } foreach (var category in viewmodel.Categories) { if (team.Categories.Any(c => c.ID == category.CategoryID)) { category.isChecked = true; } } viewmodel.Email = team.ApplicationUser.UserName; viewmodel.InstitutionID = team.InstitutionID; viewmodel.Name = team.Name; return View(viewmodel); }