public async Task <IActionResult> AddUser(int?id) { if (id == null) { return(NotFound()); } //getting the project using id var project = await _context.Projects .FirstOrDefaultAsync(m => m.Id == id); if (project == null) { return(NotFound()); } //var usersOnProject = await _userManager.GetUsersForClaimAsync(new Claim("AssignedProject", project.Id.ToString())); var vm = new ProjectsAddUserVM { ProjectId = project.Id, ProjectTitle = project.Title, Users = new SelectList(_dbContext.Users.OrderBy(u => u.Email), "Id", "Email") }; return(View(vm)); }
public async Task <IActionResult> AddUser(ProjectsAddUserVM rvm) { var user = await _userManager.FindByIdAsync(rvm.UserId); //setting values in view model in case there is an error and the view has to be returned again var project = await _context.Projects.FirstOrDefaultAsync(m => m.Id == rvm.ProjectId); rvm.Users = new SelectList(_dbContext.Users.OrderBy(u => u.Email), "Id", "Email"); rvm.ProjectId = project.Id; rvm.ProjectTitle = project.Title; if (ModelState.IsValid) { //checking if there are duplicate claims var userclaims = await _userManager.GetClaimsAsync(user); var userHasClaim = userclaims.Any(f => f.Type == "AssignedProject" && f.Value == project.Id.ToString()); if (userHasClaim) { ModelState.AddModelError(string.Empty, "User is already assigned to project"); return(View(rvm)); } //adding the claim to the user var result = await _userManager.AddClaimAsync(user, new Claim("AssignedProject", project.Id.ToString())); if (result.Succeeded) { return(RedirectToAction("Details", new { id = rvm.ProjectId.ToString() })); } foreach (var error in result.Errors) { ModelState.AddModelError(error.Code, error.Description); } } return(View(rvm)); }