简体   繁体   English

ASP.NET MVC 5从特定角色获取用户

[英]ASP.NET MVC 5 Get users from specific Role

How is it possible to show a List from all users in a specific role. 如何以特定角色显示所有用户的列表。

I attach a IdentityRole model to my View with the 'Admin' role assigned to it. 我将IdentityRole模型附加到分配了“管理员”角色的视图上。 So far I only can get the UserId. 到目前为止,我只能获取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. 问题是我也需要角色本身的数据。

If you are using ASP.NET Identity 2: 如果您使用的是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);
}

and in View: 并在视图中:

@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>
}

I found a working solution using ViewModels: 我使用ViewModels找到了一个可行的解决方案:

ViewModel: ViewModel:

public class RoleUserVM
{
    public IdentityRole Role { get; set; }
    public ICollection<ApplicationUser> Users { get; set; }
}

Controller: 控制器:

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);
}

View: 视图:

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM