如何显示特定角色中所有用户的列表。
我将一个分配了“管理员”角色的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>
}一种可能的解决方案是在控制器中创建一个用户列表,并将其附加到视图。问题是我还需要来自角色本身的数据。
发布于 2015-04-27 18:00:55
如果您使用的是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>
}发布于 2015-04-27 17:56:59
我找到了一个使用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>https://stackoverflow.com/questions/29891264
复制相似问题