public async Task <IActionResult> EditUnit(NewUnitView model, IFormCollection form, CancellationToken cancellationToken) { model.Types = await _unitsService.GetUnitTypesForDepartmentAsync(DepartmentId); model.Stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(DepartmentId); if (!await _authorizationService.CanUserModifyUnitAsync(UserId, model.Unit.UnitId)) { Unauthorized(); } var unitCheck = await _unitsService.GetUnitByNameDepartmentIdAsync(DepartmentId, model.Unit.Name); if (unitCheck != null && unitCheck.UnitId != model.Unit.UnitId) { 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(); var unit = await _unitsService.GetUnitByIdAsync(model.Unit.UnitId); var auditEvent = new AuditEvent(); auditEvent.DepartmentId = DepartmentId; auditEvent.UserId = UserId; auditEvent.Type = AuditLogTypes.UnitChanged; auditEvent.Before = unit.CloneJson(); unit.Name = model.Unit.Name; unit.Type = model.Unit.Type; if (model.Unit.StationGroupId.HasValue && model.Unit.StationGroupId.Value != 0) { unit.StationGroupId = model.Unit.StationGroupId; } else { unit.StationGroupId = null; } if (ModelState.IsValid) { await _unitsService.SaveUnitAsync(unit, cancellationToken); var roles = new List <UnitRole>(); if (unitRoleNames.Count > 0) { foreach (var roleName in unitRoleNames) { var role = new UnitRole(); role.Name = roleName; role.UnitId = unit.UnitId; roles.Add(role); } } if (roles.Count > 0) { await _unitsService.SetRolesForUnitAsync(unit.UnitId, roles, cancellationToken); } else { await _unitsService.ClearRolesForUnitAsync(unit.UnitId, cancellationToken); } auditEvent.After = unit.CloneJson(); _eventAggregator.SendMessage <AuditEvent>(auditEvent); return(RedirectToAction("Index")); } return(View(model)); }