+977-9849845061

[SOLVED] List all users with associated roles in ASP.NET Identity

View returning List of Users with their associated Roles in ASP-NET MVC

In this article, we will leanr how to list all users with Associated ROles in ASP.NET MVC 5 using Identity. ASP.NET MVC 5 does not have an inbuilt feature to list users with associated roles by default. However ASP.NET MVC have inbuilt UserManager, SignManager and RoleManager to assist this, but yet there is no prebuilt method that can list users associated with Users.

We need this feature in each of our Application as users are to be maintained along with their associated Roles. We can apply no of ideas to do this. In this article, we will learn a very simple way to list Users with their associated RoleName as in the figure below.

Step 1: Create a View Model as Users-in-Role_ViewModel

Adding Users_in_Role_ViewModel to list All the users with Associated Roles

 

Code Snippet : 

 

Step 2: Add New Method called UsersWithRoles inside ManageUsersController and add following codes.

C# Method to list users with their associated Roles in ASP.NEt MVC 5 using Identity

Code Snippet : 

context.Users represent the table AspNetUsers which has a navigation property Roles which represents the AspNetUserInRoles table. Then we perform join of context.Roles which represents the AspNetRoles table to get the role name.

 

Step 3: Now let’s add a view of UsersWithRoles method of ManageUsersController as

 

Result: 

Now the above method and view will return Users with their roles as shown in the following figure.

View returning List of Users with their associated Roles in ASP-NET MVC
View returning List of Users with their associated Roles in ASP-NET MVC

Note: You need to have the list of users associated with each role.

Source Code : https://github.com/nishanaryal/ASP.NET-MVC

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...