geekowls
geekowls

Reputation: 627

Get users against a role in Entity Framework 6

I am using the MVC built-in user roles Database to handle roles in my application. I want to show all users against a role in a list format in my view. So far I am getting a list of roles in my table, but I am unable to get users against that.

My Controller code:

[HttpGet]
[AllowAnonymous]
public ActionResult Roles()
{
    var ro = (from rl in context.Roles
              select new { Name = rl.Name, Id = rl.Id }).ToList().
              Select(x => new rolesViewModel { S2 = x.Name, S1 = context.Users.Where(o => o.Roles.Any(h => h.RoleId == x.Id))}).ToList();

    ViewBag.Roles = ro;
    return View("rolesList");
}

In my View i am using IEnumerable to display the list of roles and users against them. Roles are displayed but I really can't find a way to display the list of users.

<table class="table">
    <tr>
        <th>
            Role
        </th>
        <th>
            Assigned Users
        </th>

    </tr>
    @{ 
        var s = (IEnumerable<rolesViewModel>)ViewBag.Roles;
    }
    @foreach (var t in s)
    {
        <tr>
            <td>@t.S2</td>
            <td>@t.S1</td>
        </tr>

    }

</table>

Upvotes: 2

Views: 1108

Answers (2)

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

If you are using Identity you could list roles and users in roles by using user manager and role manager:

public ActionResult Roles()
{
    var rolemanager = new RoleManager<IdentityRole>(
        // imaging you are using default IdentityRole and RoleStore
        // otherwise use own
        new RoleStore<IdentityRole>(
             // imaging your EF context name id ApplicationDbContext
             HttpContext.GetOwinContext().Get<ApplicationDbContext>()));

    var userManager = HttpContext.GetOwinContext()
        .GetUserManager<UserManager<ApplicationUser>>();

    var rolesWithUsers = rolemanager.Roles.Select(r =>
        new RoleViewModel 
        {
            Name = r.Name,
            Users = r.Users.Select(u => userManager.FindById(u.UserId).UserName)
        });

    return View(rolesWithUsers,"rolesList");
}

Now in your view you could write something like this:

@model IEnumerable<Mynamespace.RoleViewModel>
// table header

@foreach(var item in Model)
{
    <tr>
        <td>@item.Name</td>
        <td>@string.Join(", ", item.Users)</td>
    </tr>
}

public class RoleViewModel
{
    public string Name {get; set;}
    public IEnumerable<string> Users {get; set; }
} 

Upvotes: 1

scgough
scgough

Reputation: 5252

Could you use the built in Membership/Role functionality in your view:

@{
string[] rls = Roles.GetAllRoles();
     foreach (string r in rls)
     {
        string[] usrs = Roles.GetUsersInRole(r);
        foreach (string u in usrs)
        {
        <text>
        <tr>
            <td>@u</td>
        </tr>
        </text>
        }
    }
}

Upvotes: 0

Related Questions