Search code examples
c#asp.net-mvc-5asp.net-membershipasp.net-identity

How to get list of user in a particular role?


How to get list of user in a particular role in ASP.net MVC5. I have following code but it returns all the user.

 public ActionResult Index()
  {
        var users = Context.Users.ToList();
        return View(users);
  }

I have role name "Coordinator". I just want all the users with that role.

//View File

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>
@{
    ViewBag.Title = "Index";
}

<h2>Roles Listing </h2>
<div>
    <p><strong>Username | Email</strong></p>
    @foreach (var user in Model)
    {
        <p>
            @user.UserName   |   @user.Email | @Html.ActionLink("Delete", "Delete", new { id = user.Id })
        </p>
    }
</div>

Solution

  • Assuming each user instance is of type ApplicationUser, and that you implemented Role Based authentication, you can easily filter user with specific roles like so:

    public ActionResult Index()
    {
            // Assuming that Coordinator has RoleId of 3
            var users = Context.Users.Where(x=>x.Roles.Any(y=>y.RoleId == 3)).ToList();
            return View(users);
    }