步骤
准备编辑角色用的 ViewModel
public class EditRoleViewModel
{
[Display(Name = "角色Id")]
public string Id { get; set; }
[Required]
[Display(Name = "角色名称")]
public string RoleName { get; set; }
public List<string> Users { get; set; }
public EditRoleViewModel()
{
Users = new List<string>();
}
}
EditRole Get 方法,通过传入的 Id 返回角色编辑相关信息
[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"角色 Id 为 {id} 的信息不存在,请重试。";
return View("NotFound");
}
var model = new EditRoleViewModel
{
Id = role.Id,
RoleName = role.Name
};
var users = _userManager.Users.ToList();
foreach (var user in users)
{
// 如果用户拥有此角色,请讲用户名添加到 EditRoleViewModel 的 Users 属性中
if (await _userManager.IsInRoleAsync(user, role.Name))
{
model.Users.Add(user.UserName);
}
}
return View(model);
}
编辑角色视图 ```html @model EditRoleViewModel
@{ ViewBag.Title = “编辑角色”; }
编辑角色
4. 更新角色信息
```csharp
[HttpPost]
public async Task<IActionResult> EditRole(EditRoleViewModel model)
{
var role = await _roleManager.FindByIdAsync(model.Id);
if (role == null)
{
ViewBag.ErrorMessage = $"角色 Id 为 {model.Id} 的信息不存在,请重试。";
return View("NotFound");
}
role.Name = model.RoleName;
var result = await _roleManager.UpdateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("ListRoles");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View(model);
}