public IActionResult EditUnit(NewUnitView model, IFormCollection form) { model.Types = _unitsService.GetUnitTypesForDepartment(DepartmentId); model.Stations = _departmentGroupsService.GetAllStationGroupsForDepartment(DepartmentId); if (!_authorizationService.CanUserModifyUnit(UserId, model.Unit.UnitId)) { Unauthorized(); } if (_unitsService.GetUnitByNameDepartmentId(DepartmentId, model.Unit.Name) != null && _unitsService.GetUnitByNameDepartmentId(DepartmentId, model.Unit.Name).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 = _unitsService.GetUnitById(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) { _unitsService.SaveUnit(unit); 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) { _unitsService.SetRolesForUnit(unit.UnitId, roles); } else { _unitsService.ClearRolesForUnit(unit.UnitId); } auditEvent.After = unit.CloneJson(); _eventAggregator.SendMessage <AuditEvent>(auditEvent); return(RedirectToAction("Index")); } return(View(model)); }