public ActionResult Create(Command command, FormCollection formCollection, string[] selectedCommandParts) { if (ModelState.IsValid) { UpdateCommandParts(selectedCommandParts, command); db.Commands.Add(command); db.SaveChanges(); return RedirectToAction("Index"); } return View(command); }
private void UpdateCommandParts(string[] selectedCommandParts, Command commandToUpdate) { commandToUpdate.CommandParts = new List<CommandPart>(); if (selectedCommandParts == null) { return; } var selectedCommandPartsHS = new HashSet<string>(selectedCommandParts); var commandParts = new HashSet<int>(commandToUpdate.CommandParts.Select(p => p.CommandPartID)); foreach (var part in db.CommandParts) { if (selectedCommandPartsHS.Contains(part.CommandPartID.ToString())) { if (!commandParts.Contains(part.CommandPartID)) { commandToUpdate.CommandParts.Add(part); } } else { if (commandParts.Contains(part.CommandPartID)) { commandToUpdate.CommandParts.Remove(part); } } } }
// // GET: /Command/Create public ActionResult Create() { var command = new Command(); PopulateSelectedCommandParts(command); return View(command); }
private void PopulateSelectedCommandParts(Command command) { var allCommandParts = db.CommandParts; var selectedCommandParts = new HashSet<int>(); if (command.CommandParts != null) { selectedCommandParts = new HashSet<int>(command.CommandParts.Select(p => p.CommandPartID)); } //var selectedCommandParts = // new HashSet<int>(command.CommandParts.Select(p => p.CommandPartID)); var viewModel = new List<SelectedCommandPartData>(); foreach (var part in allCommandParts) { viewModel.Add(new SelectedCommandPartData { CommandPartID = part.CommandPartID, part = part.part, Assigned = selectedCommandParts.Contains(part.CommandPartID) }); } ViewBag.CommandParts = viewModel; }