Reputation: 1343
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.
Upvotes: 0
Views: 9209
Reputation: 11544
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>
}
Upvotes: 8
Reputation: 1343
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>
Upvotes: 2