2

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>
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Nakib
  • 4,593
  • 7
  • 23
  • 45

2 Answers2

1

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);
}
Omer
  • 684
  • 4
  • 14
  • Getting Following Error 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole' does not contain a definition for 'RoleName' and no extension method 'RoleName' accepting a first argument of type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole' could be found (are you missing a using directive or an assembly reference?) – Nakib Dec 03 '14 at 20:15
  • see edit. You will need to find out the role id for coordinator. – Omer Dec 03 '14 at 20:21
  • Use the Role Manager, see this SO answer: http://stackoverflow.com/a/22212506/260079 – Omer Dec 03 '14 at 20:49
0

First create ApplicationRoleManager class to manage roles like below.

    public class ApplicationRoleManager : RoleManager<IdentityRole, string>
    {
        public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
            : base(roleStore)
        {
        }

        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            return new ApplicationRoleManager(new RoleStore<IdentityRole, string, IdentityUserRole>(context.Get<ApplicationDbContext>()));
        }
    }

Then add following code to Startup.Auth.cs class in order to create instance of RoleManager during owin start up.

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

Your controller action should be like this.

  public ActionResult Index()
  {
        var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        var users = roleManager.FindByName("Coordinator").Users;

        return View(users);
  }

Hope this helps.

DSR
  • 4,588
  • 29
  • 28