Identity用户管理入门四(修改、删除用户)
修改用户不能修改Id及用户名所以创建视图模型时需要去除,新增用户跟修改用户基本视图一直,所以不再做演示
一、新建UpdateUserViewModel视图模型
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Shop.ViewModel { public class UpdateUserViewModel { [EmailAddress(ErrorMessage = "邮箱格式不正确")] [DisplayName("邮箱")] public string Email { get; set; } [DisplayName("手机号")] [MinLength(11, ErrorMessage = "手机位数不足11位"), StringLength(11)] public string PhoneNumber { get; set; } [Required(ErrorMessage = "密码不能为空")] [DataType(DataType.Password)] [DisplayName("密码")] public string PasswordHash { get; set; } } }
二、修改用户方法
[HttpPost] public async Task<IActionResult> EditUser(string id, UpdateUserViewModel input) {
//查询是否存在用户 var user = await _userManager.FindByIdAsync(id); if (user != null) { user.Email = input.Email; user.PhoneNumber = input.PhoneNumber; //密码为空则不修改密码 if (input.PasswordHash != null) { user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, input.PasswordHash); } //更新用户 var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { return RedirectToAction("Index"); } } return View(input); }
三、删除用户
public async Task<IActionResult> Delete(string id) { var user = await _userManager.FindByIdAsync(id); if (user != null) { var result = await _userManager.DeleteAsync(user); if (result.Succeeded) { return RedirectToAction("Index"); } } return StatusCode(403); }
本文来自博客园,作者:liessay,转载请注明原文链接:https://www.cnblogs.com/liessay/p/13207713.html