我试图找出如何将所有用户及其角色放入一个漂亮的有条理的表中,看到了许多不同的方法,但没有一种对我有用。我至少有一点努力...任何可以帮助我的人吗?
通过此代码,我可以获得所有角色:
var context = new ApplicationDbContext();
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var roles = (from r in roleManager.Roles select r.Name).ToList();
ViewBag.Roles = roles.ToList();
并使用此代码获得所有注册用户:
var context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var users = (from u in userManager.Users select u.UserName).ToList();
ViewBag.Users = users.ToList();
最后用这段代码我得到所有用户的ID
var context = new ApplicationDbContext();
var user = (from u in userManager.Users select u.Id).ToList();
ViewBag.id = user.ToList();
但是如何获得所有用户的角色?我真的不知道
这是一个获取用户列表(带有用户名)和关联角色列表的选项。
控制器:
public ActionResult GetRoles()
{
var userRoles = new List<RolesViewModel>();
var context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
//Get all the usernames
foreach (var user in userStore.Users)
{
var r = new RolesViewModel
{
UserName = user.UserName
};
userRoles.Add(r);
}
//Get all the Roles for our users
foreach (var user in userRoles)
{
user.RoleNames = userManager.GetRoles(userStore.Users.First(s=>s.UserName==user.UserName).Id);
}
return View(userRoles);
}
视图模型
public class RolesViewModel
{
public IEnumerable<string> RoleNames { get; set; }
public string UserName { get; set; }
}
视图:简单的一个
@model IEnumerable<StackOverflow.Models.RolesViewModel>
@foreach (var user in Model.ToList())
{
<div> @user.UserName -- </div>
foreach (var role in user.RoleNames)
{
<div> @role </div>
}
<br />
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句