public async Task <IActionResult> SelectOrChangeContactName(SelectOrChangeContactNameViewModel vm) { var epaoid = _contextAccessor.HttpContext.User.FindFirst("http://schemas.portal.com/epaoid")?.Value; try { var organisation = await _organisationsApiClient.GetEpaOrganisation(epaoid); var primaryContact = !string.IsNullOrEmpty(vm.PrimaryContact) ? await _contactsApiClient.GetByUsername(vm.PrimaryContact) : null; if (vm.ActionChoice == "Save") { if (ModelState.IsValid) { if (string.Equals(vm.PrimaryContact, organisation.PrimaryContact)) { return(RedirectToAction(nameof(OrganisationDetails))); } if (organisation.Id != primaryContact?.OrganisationId) { ModelState.AddModelError(nameof(SelectOrChangeContactNameViewModel.PrimaryContact), "The contact name cannot be changed to a contact of a different organisation"); } } if (!ModelState.IsValid) { return(RedirectToAction(nameof(SelectOrChangeContactName))); } vm = new SelectOrChangeContactNameViewModel { Contacts = null, PrimaryContact = vm.PrimaryContact, PrimaryContactName = primaryContact.DisplayName }; return(View("SelectOrChangeContactNameConfirm", vm)); } else if (vm.ActionChoice == "Confirm") { var userId = _contextAccessor.HttpContext.User.FindFirst("UserId").Value; var request = new UpdateEpaOrganisationPrimaryContactRequest { PrimaryContactId = primaryContact.Id, OrganisationId = organisation.OrganisationId, UpdatedBy = Guid.Parse(userId) }; var notifiedContacts = await _organisationsApiClient.UpdateEpaOrganisationPrimaryContact(request); if (notifiedContacts != null) { vm = new SelectOrChangeContactNameViewModel { Contacts = notifiedContacts, PrimaryContact = vm.PrimaryContact, PrimaryContactName = primaryContact.DisplayName }; return(View("SelectOrChangeContactNameUpdated", vm)); } else { ModelState.AddModelError(nameof(SelectOrChangeContactNameViewModel.PrimaryContact), "Unable to update the contact name at this time."); return(RedirectToAction(nameof(SelectOrChangeContactName))); } } } catch (EntityNotFoundException e) { _logger.LogWarning(e, "Failed to find organisation"); return(RedirectToAction(nameof(HomeController.NotRegistered), nameof(HomeController).RemoveController())); } return(RedirectToAction(nameof(OrganisationDetails))); }