public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Craftsman craftsman = db.Craftsmen.Find(id); if (craftsman == null) { return(HttpNotFound()); } var result = from g in db.Guitars select new { g.id, g.Name, Checked = ((from gTOc in db.GuitarToCraftsmen where (gTOc.CraftsmanID == id) && (gTOc.GuitarID == g.id) select gTOc).Count() > 0 ) }; var myViewModel = new CraftsmenViewModel(); myViewModel.CrafrsmanID = id.Value; myViewModel.Name = craftsman.Name; myViewModel.Surname = craftsman.Surname; myViewModel.Description = craftsman.Description; myViewModel.Address = craftsman.Address; var CheckBoxList = new List <CheckboxViewModel>(); foreach (var item in result) { CheckBoxList.Add(new CheckboxViewModel { id = item.id, Name = item.Name, Checked = item.Checked }); } myViewModel.Guitars = CheckBoxList; return(View(myViewModel)); }
public ActionResult Edit(CraftsmenViewModel craftsman) { if (ModelState.IsValid) { var myCraftsman = db.Craftsmen.Find(craftsman.CrafrsmanID); myCraftsman.Name = craftsman.Name; myCraftsman.Surname = craftsman.Surname; myCraftsman.Description = craftsman.Description; myCraftsman.Address = craftsman.Address; foreach (var item in db.GuitarToCraftsmen) { if (item.CraftsmanID == craftsman.CrafrsmanID) { db.Entry(item).State = System.Data.Entity.EntityState.Deleted; } } foreach (var item in craftsman.Guitars) { if (item.Checked) { db.GuitarToCraftsmen.Add(new GuitarToCraftsman() { CraftsmanID = craftsman.CrafrsmanID, GuitarID = item.id }); } } //db.Entry(craftsman).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(craftsman)); }