Пример #1
0
        public async Task<IActionResult> Edit(EditUserViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
            {
                return Unauthorized();
            }

            CleanViewModel(model);

            var currentUser = await _userManager.FindByIdAsync(model.Id.ToString());

            if (currentUser == null)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                if ((await _userManager.FindByNameAsync(model.UserName))?.Id != currentUser.Id)
                {
                    ModelState.AddModelError(string.Empty, T["The user name is already used."]);
                }

                if ((await _userManager.FindByEmailAsync(model.Email))?.Id != currentUser.Id)
                {
                    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();
                currentUser.RoleNames = roleNames;
                currentUser.UserName = model.UserName;
                currentUser.Email = model.Email;

                var result = await _userManager.UpdateAsync(currentUser);
                if (result.Succeeded)
                {
                    _notifier.Success(TH["User updated successfully"]);
                    return RedirectToAction(nameof(Index));
                }

                _session.Cancel();

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, T[error.Description]);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #2
0
 public void CleanViewModel(EditUserViewModel model)
 {
     model.UserName = model.UserName?.Trim();
     model.Email = model.Email?.Trim();
 }
Пример #3
0
        public async Task<IActionResult> Edit(string id)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
            {
                return Unauthorized();
            }

            var currentUser = await _userManager.FindByIdAsync(id);

            if (currentUser == null)
            {
                return NotFound();
            }

            var roleNames = await GetRoleNamesAsync();
            var roles = roleNames.Select(x => new RoleViewModel { Role = x, IsSelected = currentUser.RoleNames.Contains(x, StringComparer.OrdinalIgnoreCase) }).ToArray();

            var model = new EditUserViewModel
            {
                Id = currentUser.Id,
                Email = currentUser.Email,
                UserName = currentUser.UserName,
                Roles = roles
            };

            return View(model);
        }