1

I want to show all users assigned to a specific role in the view:

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>

<table id="tbrole" style="width:100%; border:dotted 1px; background-color:gainsboro; padding-left:10px;">

                @foreach (var role in Model)
                {
                    <tr>
                        <td style="width:100%; border:dotted 1px;">
                            @role.Name<br />
                            <ul>
                                @foreach (var userInRole in role.Users)
                                {
                                    <li>@usersInRole.UserId</li>
                                }
                            </ul>
                            @if (role.Name != "Admin")
                            {
                                @Html.ActionLink("Delete", "Delete", new { id = role.Id }, new { style = "float:right;", @class = "glyphicon glyphicon-trash" })
                            }
                        </td>
                    </tr>}
            </table>

How to access the user module (email, username, address..etc) using UserId property

mshwf
  • 7,009
  • 12
  • 59
  • 133
  • You will need to use a view model to add the required users - http://stackoverflow.com/questions/29891264/asp-net-mvc-5-get-users-from-specific-role – James P Oct 31 '16 at 13:37

2 Answers2

0

It is not recommended to bind db model to view, Create a View Model contains properties you need in your view and fill it in the controller and bind it to your view.

  • // Get Roles and UserIds.
  • // Get Users by Roles.UsersIds using Contains.
Ahmed
  • 1,542
  • 2
  • 13
  • 21
  • What do you mean by >It is not recommended to bind db model to view? I saw some tutorials from MSDN that took this approach – mshwf Oct 31 '16 at 15:06
  • 1
    tutorial is just to learn you but real project with big scale is something diffirent, Bind DB model directly has a lot of problems (ex: if you want to add some custom attributes above your properties or custom validation .. ) http://stackoverflow.com/questions/18608452/mvc-4-how-pass-data-correctly-from-controller-to-view http://softwareengineering.stackexchange.com/questions/257507/should-an-asp-net-mvc-application-directly-use-entity-framework-as-the-model – Ahmed Oct 31 '16 at 15:10
0

This solved it:

var users = context.Users        
    .Where(x => x.Roles.Select(y => y.Id).Contains(roleId))
    .ToList();

The original answer: https://stackoverflow.com/a/23854281/6197785

Community
  • 1
  • 1
mshwf
  • 7,009
  • 12
  • 59
  • 133