public async Task <IActionResult> Create([Bind("Name,Description")] Project model) { if (ModelState.IsValid) { Project project = new Project { Name = model.Name, Description = model.Description, IsOpen = true }; ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User); var projectUser = new ProjectApplicationUser { Project = project, ApplicationUser = user }; project.ProjectApplicationUsers.Add(projectUser); user.ProjectApplicationUsers.Add(projectUser); _DbContext.Projects.Add(project); await _userManager.UpdateAsync(user); await _DbContext.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(model)); }
public async Task <IActionResult> AssignUser(List <EditUsersInRoleViewModel> model, int id) { try { var project = _DbContext.Projects.Where(t => t.Id == id).Include(t => t.ProjectApplicationUsers).SingleOrDefault(); if (project == null) { return(NotFound("No project ID provided. This might be bad.")); } for (int i = 0; i < model.Count; i++) { var user = await _userManager.FindByIdAsync(model[i].UserId); if (user == null) { return(NotFound("No user ID provided. This might be bad.")); } if (model[i].IsSelected && !project.ProjectApplicationUsers.Any(tau => tau.ApplicationUser == user)) { ProjectApplicationUser pau = new ProjectApplicationUser(); pau.ApplicationUser = user; pau.Project = project; project.ProjectApplicationUsers.Add(pau); _DbContext.Projects.Update(project); //maybe better to put it before return, im too tired and afraid at this point to optimize _DbContext.SaveChanges(); } else if (!model[i].IsSelected && project.ProjectApplicationUsers.Any(tau => tau.ApplicationUser == user)) { //not even going in here var found = project.ProjectApplicationUsers.FirstOrDefault(x => x.ApplicationUser == user); if (found != null) { project.ProjectApplicationUsers.Remove(found); } _DbContext.Projects.Update(project); //maybe better to put it before return, im too tired and afraid at this point to optimize _DbContext.SaveChanges(); } else { continue; } } return(RedirectToAction("Details", new { id = id })); } catch (Exception e) { return(Json(new { e.Message })); } }