here the system is like one user may have many roles so now I am able to list users, but I want to list roles too for example
this controller will list only users,
public ActionResult listOfRolesForUser()
{
RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ndb));
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ndb));
ViewBag.AllUsers = UserManager.Users.ToList();
return View();
}
and this is view or listOfRolesForUser.cshtml
@{
ViewBag.Title = "listOfRolesForUser";
}
<h2>listOfRolesForUser</h2>
<table border="1">
<tr>
<td>User name</td>
<td>Roles</td>
</tr>
@foreach (var item2 in ViewBag.AllUsers)
{
<tr>
<td>@item2.UserName</td>
<td>here i need to list related role too</td>
</tr>
}
</table>
now how I will be able to list like:
To retrieve both Users and Roles , you can store both lists and pass to a view model.
public ActionResult Index()
{
using (var context = new ApplicationDbContext())
{
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var users = UserManager.Users;
var roles = new List<string>();
// retrieve roles for each user
foreach (var user in users)
{
string str = "";
foreach (var role in UserManager.GetRoles(user.Id))
{
str = (str == "") ? role.ToString() : str + " - " + role.ToString();
}
roles.Add(str);
}
var model = new HomeViewModel()
{
// create view model with these fields
users = users.ToList(),
roles = roles.ToList()
};
return View(model);
}
}
Using the view model populate the table, implement Delete
method in HomeController
and navigate to Home/Delete
url through an ajax call.
@model WebApplication1.Models.HomeViewModel
<h2>listOfRolesForUser</h2>
<table border="1">
<tr>
<td>User name</td>
<td>Roles</td>
<td>Actions</td>
</tr>
@{
int i = 0;
foreach (var item in Model.users)
{
<tr id="@item.Id">
<td>@item.UserName</td>
<td>@Model.roles[i]</td>
<td>
<a href="#" onclick="deleteUser('@item.Id')" id="btnDelete" data-toggle="modal" data-target="#deleteModal" title="Delete">
Delete
</a>
</td>
</tr>
i++;
}
}
</table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.