ASP.NET MVC 5 Get users from specific Role

亡梦爱人 提交于 2019-12-19 11:57:10

问题


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


回答1:


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

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



回答2:


I found a working solution using ViewModels:

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>


来源:https://stackoverflow.com/questions/29891264/asp-net-mvc-5-get-users-from-specific-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!