private void UpdateCowboyKills(string[] selectedIndians, Cowboys cowboyToUpdate) { if (selectedIndians == null) { cowboyToUpdate.Indians = new List <Indians>(); return; } var selectedCowboysHS = new HashSet <string>(selectedIndians); var indianKills = new HashSet <int> (cowboyToUpdate.Indians.Select(i => i.Id)); foreach (var indian in db.Indians) { if (selectedCowboysHS.Contains(indian.Id.ToString())) { if (!indianKills.Contains(indian.Id)) { cowboyToUpdate.Indians.Add(indian); } } else { if (indianKills.Contains(indian.Id)) { cowboyToUpdate.Indians.Remove(indian); } } } }
public ActionResult DeleteConfirmed(int id) { Cowboys cowboys = db.Cowboys.Include(c => c.Indians).Single(c => c.Id == id); db.Cowboys.Remove(cowboys); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Stats(int?id) { Cowboys cowboy = db.Cowboys.Include(c => c.Indians).Single(c => c.Id == id); if (id.HasValue && cowboy == null) { return(HttpNotFound()); } return(View(cowboy)); }
public ActionResult Create([Bind(Include = "Id,Cowboy_Name,Indians")] Cowboys cowboys, string[] selectedIndians) { if (ModelState.IsValid) { UpdateCowboyKills(selectedIndians, cowboys); db.Cowboys.Add(cowboys); db.SaveChanges(); return(RedirectToAction("Index")); } PopulateAssignedKillData(cowboys); return(View(cowboys)); }
// GET: Cowboys/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Cowboys cowboys = db.Cowboys.Include(c => c.Indians).Single(c => c.Id == id); if (cowboys == null) { return(HttpNotFound()); } return(View(cowboys)); }
// GET: Cowboys/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Cowboys cowboys = db.Cowboys.Include(c => c.Indians).Single(c => c.Id == id); PopulateAssignedKillData(cowboys); if (cowboys == null) { return(HttpNotFound()); } return(View(cowboys)); }
public ActionResult Edit([Bind(Include = "Id,Cowboy_Name,Indians")] Cowboys cowboys, string[] selectedIndians) { if (ModelState.IsValid) { //var cowboy = db.Cowboys.Include( c => c.Indians ).Single( c => c.Id == cowboys.Id ); db.Cowboys.Attach(cowboys); db.Entry(cowboys).Collection(x => x.Indians).Load(); UpdateCowboyKills(selectedIndians, cowboys); db.Entry(cowboys).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } PopulateAssignedKillData(cowboys); return(View(cowboys)); }
private void PopulateAssignedKillData(Cowboys cowboy) { var allIndians = db.Indians; var indianKills = new HashSet <int>(cowboy.Indians.Select(i => i.Id)); var kills = new List <KilledViewModel>(); foreach (var indian in allIndians) { kills.Add(new KilledViewModel { Id = indian.Id, Name = indian.Indian_Name, IsAssigned = indianKills.Contains(indian.Id) }); } ViewBag.Killed = kills; }