public ActionResult BeltAcheived(CustomerBeltViewModel cb) { var belts = db.CustomerBelts.Where(c => c.CustomerId == cb.CustomerId).ToList(); foreach (var belt in cb.Belts) { // get the cb already in database var customerBelt = belts.FirstOrDefault(b => b.BeltId == belt.Id); // If we don't have a customer belt and it has been achieved add it. if (customerBelt == null && belt.BeltAchieved) { db.CustomerBelts.Add(new CustomerBelt { BeltId = belt.Id, CustomerId = cb.CustomerId.Value, Id = Guid.NewGuid(), DateAchieved = DateTime.Now }); } // If a customer belt has been removed if (customerBelt != null && !belt.BeltAchieved) { db.CustomerBelts.Remove(customerBelt); } } db.SaveChanges(); return(RedirectToAction("CustomerBelts", new { customerId = cb.CustomerId })); }
public ActionResult CustomerBelts(Guid?customerId) { if (!customerId.HasValue) { RedirectToAction(""); } var model = new CustomerBeltViewModel { CustomerBelts = db.CustomerBelts .Where(cb => cb.CustomerId == customerId.Value) .Include(c => c.Customer).ToList(), Belts = db.Belts.ToList() }; // Set the boolean flags the checkbox will use. foreach (var customerBelt in model.CustomerBelts) { customerBelt.Belt.BeltAchieved = true; } return(View(model)); }