public async Task<IActionResult> Create(CreateUserViewModel model) { CleanViewModel(model); if (ModelState.IsValid) { if (await _userManager.FindByNameAsync(model.UserName) != null) { ModelState.AddModelError(string.Empty, T["The user name is already used."]); } if (await _userManager.FindByEmailAsync(model.Email) != null) { ModelState.AddModelError(string.Empty, T["The email is already used."]); } } if (ModelState.IsValid) { var roleNames = model.Roles.Where(x => x.IsSelected).Select(x => x.Role).ToList(); var user = new User { UserName = model.UserName, Email = model.Email, RoleNames = roleNames }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { _notifier.Success(TH["User created successfully"]); return RedirectToAction(nameof(Index)); } _session.Cancel(); foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return View(model); }
public void CleanViewModel(CreateUserViewModel model) { model.UserName = model.UserName?.Trim(); model.Email = model.Email?.Trim(); }
public async Task<IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers)) { return Unauthorized(); } var roleNames = await GetRoleNamesAsync(); var roles = roleNames.Select(x => new RoleViewModel { Role = x }).ToArray(); var model = new CreateUserViewModel { Roles = roles }; return View(model); }