I want to have list of all the users registered on my site with their roles.
Id | Name | Role
1 | ABC | Admin
2 | DEF | User
Something like this, I have made Roles controller in which all the roles is listed.
public ActionResult Index()
{
var roles = context.Roles.ToList();
return View(roles);
}
In View
@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
@{
ViewBag.Title = "Index";
}
<div>
@foreach (var role in Model)
{
<p>
<strong>@role.Name | </strong>
</p>
}
</div>
This will list all the roles but i want user's list with their roles.
Please give any solution, Thanks
GetRoles Usage Identity. GetUserId(); // get user roles List<string> roles = userManager. GetRoles(userId). ToList();
ASP.NET Identity is the membership system for authentication and authorization of the users by building an ASP.NET application. The ASP.NET Identity is a fresh look at what the membership system should be when you are building modern applications for the web, phone or tablet.
GetRolesForUser Method (System. Web. Security) Gets a list of the roles that a user is in.
Create a new class called UserViewModel. This will act as a view model for your page.
public class GroupedUserViewModel
{
public List<UserViewModel> Users {get; set;}
public List<UserViewModel> Admins {get; set;}
}
public class UserViewModel
{
public string Username {get; set;}
public string Roles {get; set;}
}
In the controller's action method, get the list of users along with their roles and map that to the UserViewModel.
public ActionResult Index()
{
var allusers = context.Users.ToList();
var users = allusers.Where(x=>x.Roles.Select(role => role.Name).Contains("User")).ToList();
var userVM = users.Select(user=>new UserViewModel{Username = user.FullName, Roles = string.Join(",", user.Roles.Select(role=>role.Name))}).ToList();
var admins = allusers.Where(x=>x.Roles.Select(role => role.Name).Contains("Admin")).ToList();
var adminsVM = admins.Select(user=>new UserViewModel{Username = user.FullName, Roles = string.Join(",", user.Roles.Select(role=>role.Name))}).ToList();
var model = new GroupedUserViewModel{Users = userVM, Admins = adminsVM};
return View(model);
}
Then use the new model in the view. Make sure to use correct namespace here where you defined your view model.
@model Models.GroupedUserViewModel
@{
ViewBag.Title = "Index";
}
<div>
@foreach (var user in Model.Admins)
{
<p>
<strong>@user.Username | @user.Roles </strong>
</p>
}
@foreach (var user in Model.Users)
{
<p>
<strong>@user.Username | @user.Roles </strong>
</p>
}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With