![](/img/trans.png)
[英]How to assign user roles and hide buttons from users who are not in a role, asp.net
[英]mvc 5 asp.net identity role and users, how to lest both in order user with it's roles and remove
這里的系統就像一個用戶可能有很多角色,所以現在我可以列出用戶,但是我也想列出角色
該控制器將僅列出用戶,
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>
現在我將如何像這樣列出:
要同時檢索“ 用戶”和“ 角色” ,您可以存儲兩個列表並傳遞給視圖模型。
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);
}
}
使用視圖模型填充表,在HomeController
實現Delete
方法,並通過ajax調用導航到Home/Delete
url。
@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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.