public IActionResult NewUnit(NewUnitView model, IFormCollection form) { model.Types = _unitsService.GetUnitTypesForDepartment(DepartmentId); model.Stations = _departmentGroupsService.GetAllStationGroupsForDepartment(DepartmentId); if (_unitsService.GetUnitByNameDepartmentId(DepartmentId, model.Unit.Name) != null) { ModelState.AddModelError("Name", "Unit with that name already exists."); } var unitRoleNames = (from object key in form.Keys where key.ToString().StartsWith("unitRole_") select form[key.ToString()]).ToList(); if (ModelState.IsValid) { model.Unit.DepartmentId = DepartmentId; if (model.Unit.StationGroupId.HasValue && model.Unit.StationGroupId.Value == 0) { model.Unit.StationGroupId = null; } model.Unit = _unitsService.SaveUnit(model.Unit); var roles = new List <UnitRole>(); if (unitRoleNames.Count > 0) { foreach (var roleName in unitRoleNames) { var role = new UnitRole(); role.Name = roleName; role.UnitId = model.Unit.UnitId; roles.Add(role); } } if (roles.Count > 0) { _unitsService.SetRolesForUnit(model.Unit.UnitId, roles); } var auditEvent = new AuditEvent(); auditEvent.DepartmentId = DepartmentId; auditEvent.UserId = UserId; auditEvent.Type = AuditLogTypes.UnitAdded; auditEvent.After = model.Unit.CloneJson(); _eventAggregator.SendMessage <AuditEvent>(auditEvent); _eventAggregator.SendMessage <UnitAddedEvent>(new UnitAddedEvent() { DepartmentId = DepartmentId, Unit = model.Unit }); return(RedirectToAction("Index")); } return(View(model)); }