繁体   English   中英

将所有用户及其角色放入asp.net mvc表中

[英]Get all users and their roles they got into a table asp.net mvc

我试图找出如何让所有用户和他们的角色进入一个很好的组织表,看到许多不同的方式,但没有一个对我有用。 我至少在最重要的路上得到了升功...任何可以帮助我的人?

使用此代码,我将获得所有角色:

        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 />
}

我相信您正在使用AspNetUserRoles表来管理用户和角色。 您可以使用EF和Linq优化网格中用户/角色的显示 -

[GridAction]
public ActionResult _GetUsers()

{
    var users = from user in xcsnEntities.Users
                select new
                {
                    Role = user.Roles.FirstOrDefault().RoleName,
                    IsApproved = user.Membership.IsApproved,
                    Email = user.Membership.Email,
                    UserName = user.UserName
                };

    return View(new GridModel(users));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM