我必须在我的控制器中使用它来列出所有用户:
public IActionResult ListUsers(){
var users = _application.Users.ToList();
return View(users);
}
但我似乎无法从aspnetroles表中添加ROLE字段..它应该是一个简单的连接,但我尝试过的每次尝试都失败了,就像这样:
public async Task<IActionResult> Edit(string id)
{
var applicationUser = await _context.ApplicationUser.SingleOrDefaultAsync(m => m.Id == id);
var model = new UsuariosViewModel
{
CC = applicationUser.CC,
Apellido = applicationUser.Apellido,
Nombre = applicationUser.Nombre,
Rol = await _userManager.GetRolesAsync(applicationUser)
};
return View(model);
}
该方法应该如何?
此外,加入后视图应该如何?
答案 0 :(得分:0)
用户可能有多个角色
这是行动:
public async Task<IActionResult> UsersRolesList()
{
var AllUsers = _application.Users.ToList();
UsersAndRolesViewModel UserAndRoleViewModel = new UsersAndRolesViewModel();
List<UserAndRoleViewModel> AllUsersAndRoles = new List<UserAndRoleViewModel>();
foreach (var usr in AllUsers)
{
var model = new UserAndRoleViewModel
{
UserName = usr.UserName,
Roles = await userManager.GetRolesAsync(usr)
};
AllUsersAndRoles.Add(model);
}
UserAndRoleViewModel.UserAndRole = AllUsersAndRoles;
return View(UserAndRoleViewModel);
}
和这个观点:
@model UsersAndRolesViewModel
<table style="width:100%">
@foreach (var usr in Model.UserAndRole)
{
<tr>
<td>
UserName:
@usr.UserName
</td>
<td>
Roles:
<table>
<tr>
@foreach (var role in usr.Roles)
{
<td>
Role Name: @role
</td>
}
</tr>
</table>
</td>
</tr>
}
</table>
这是ViewModel
public class UserAndRoleViewModel
{
public string UserName { get; set; }
public IList<string> Roles { get; set; }
}
public class UsersAndRolesViewModel
{
public List<UserAndRoleViewModel> UserAndRole { get; set; }
}