[英]ASP.NET MVC 5 Get users from specific Role
如何以特定角色顯示所有用戶的列表。
我將IdentityRole模型附加到分配了“管理員”角色的視圖上。 到目前為止,我只能獲取UserId。
@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
@Html.DisplayNameFor(model => model.Name) // Shows 'Admin'
@foreach (var item in Model.Users)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserId)
</td>
</tr>
}
一種可能的解決方案是在控制器中創建用戶列表,並將其附加到視圖。 問題是我也需要角色本身的數據。
如果您使用的是ASP.NET Identity 2:
public ActionResult UserList(string roleName)
{
var context = new ApplicationDbContext();
var users = from u in context.Users
where u.Roles.Any(r => r.Role.Name == roleName)
select u;
ViewBag.RoleName = roleName;
return View(users);
}
並在視圖中:
@model Microsoft.AspNet.Identity.EntityFramework.IdentityUser // or ApplicationUser
@Html.DisplayNameFor(model => ViewBag.RoleName) // Shows 'Admin'
@foreach (var item in Model.Users)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
</tr>
}
我使用ViewModels找到了一個可行的解決方案:
ViewModel:
public class RoleUserVM
{
public IdentityRole Role { get; set; }
public ICollection<ApplicationUser> Users { get; set; }
}
控制器:
public async Task<ActionResult> Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var role = await RoleManager.FindByIdAsync(id);
var users = new List<ApplicationUser>();
foreach (var user in UserManager.Users.ToList())
{
if (await UserManager.IsInRoleAsync(user.Id, role.Name))
{
users.Add(user);
}
}
RoleUserVM vm = new RoleUserVM();
vm.Users = users;
vm.Role = role;
return View(vm);
}
視圖:
@model AspnetIdentitySample.Models.RoleUserVM
@Html.DisplayFor(model => model.Role.Name)
<table class="table table-striped">
@foreach (var item in Model.Users)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
</tr>
}
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.