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);
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM