I want get just in Role users in mvc, I tried everything. As you know AspNetUserRoles
is a mapping table (many-to-many), so it's not generated in EDMX (by design, it does not have primary key). Also we can't use Role table(?). Please consider my model in view.
Here is my last try:
public async Task<ActionResult> Roles()
{
var list = context.Users.Include(u => u.Roles);
var user = new List<ApplicationUser>();
foreach(var u in list)
{
if(u.Roles!= null)
{
user.Add(u);
}
}
return View(user);
}
and here is my view:
@model IEnumerable<Site.Models.ApplicationUser>
@{
Layout = null;
}
<h2>List of users with Roles:</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th>
@Html.DisplayNameFor(model => model.Roles)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<th>
@Html.DisplayFor(modelItem => item.Roles)
</th>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
Try this one out:
var usersList = new List<ApplicationUser>();
foreach (ApplicationUser user in UserManager.Users)
{
var roles = await UserManager.GetRolesAsync(user.Id);
if(roles.contains("Admin"))
{
usersList.Add(user);
}
}
This one should only return users who has Admin role. I hope it helps.