ASP.NET MVC 5 从特定角色获取用户 [英] ASP.NET MVC 5 Get users from specific Role

查看:22
本文介绍了ASP.NET MVC 5 从特定角色获取用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示特定角色中所有用户的列表.

How is it possible to show a List from all users in a specific role.

我将 IdentityRole 模型附加到我的视图,并为其分配了管理员"角色.到目前为止,我只能获取 UserId.

I attach a IdentityRole model to my View with the 'Admin' role assigned to it. So far I only can get the 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>
}

一个可能的解决方案是在控制器中创建一个用户列表并将其附加到视图.问题是我还需要角色本身的数据.

A possible solution would be to create a List of the users in the controller and attach this to the View. The problem would be that I also need data from the Role itself.

推荐答案

如果您使用的是 ASP.NET Identity 2:

If you are using 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>
}

这篇关于ASP.NET MVC 5 从特定角色获取用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆