此处系统就像一个用户可能有多个角色所以现在我可以列出用户,但我也想列出角色,例如
此控制器将仅列出用户
public ActionResult listOfRolesForUser()
{
RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ndb));
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ndb));
ViewBag.AllUsers = UserManager.Users.ToList();
return View();
}
这是view或listOfRolesForUser.cshtml
@{
ViewBag.Title = "listOfRolesForUser";
}
<h2>listOfRolesForUser</h2>
<table border="1">
<tr>
<td>User name</td>
<td>Roles</td>
</tr>
@foreach (var item2 in ViewBag.AllUsers)
{
<tr>
<td>@item2.UserName</td>
<td>here i need to list related role too</td>
</tr>
}
</table>
现在我将如何列出如下:
答案 0 :(得分:0)
要检索用户和角色,您可以存储这两个列表并传递给视图模型。
public ActionResult Index()
{
using (var context = new ApplicationDbContext())
{
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var users = UserManager.Users;
var roles = new List<string>();
// retrieve roles for each user
foreach (var user in users)
{
string str = "";
foreach (var role in UserManager.GetRoles(user.Id))
{
str = (str == "") ? role.ToString() : str + " - " + role.ToString();
}
roles.Add(str);
}
var model = new HomeViewModel()
{
// create view model with these fields
users = users.ToList(),
roles = roles.ToList()
};
return View(model);
}
}
使用视图模型填充表格,在Delete
中实施HomeController
方法,然后通过ajax调用导航到Home/Delete
网址。
@model WebApplication1.Models.HomeViewModel
<h2>listOfRolesForUser</h2>
<table border="1">
<tr>
<td>User name</td>
<td>Roles</td>
<td>Actions</td>
</tr>
@{
int i = 0;
foreach (var item in Model.users)
{
<tr id="@item.Id">
<td>@item.UserName</td>
<td>@Model.roles[i]</td>
<td>
<a href="#" onclick="deleteUser('@item.Id')" id="btnDelete" data-toggle="modal" data-target="#deleteModal" title="Delete">
Delete
</a>
</td>
</tr>
i++;
}
}
</table>