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

标签 c# asp.net asp.net-mvc user-roles

我试图弄清楚如何将所有用户及其角色放入一个组织良好的表格中,看到了许多不同的方法,但没有一个对我有用。至少我已经掌握了一些知识...有人可以帮助我吗?

通过这段代码我得到了所有的角色:

        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();

但是我如何让所有用户拥有他们的角色?我真的想不通

最佳答案

这是获取用户列表(带有用户名)和相关角色列表的一个选项。

Controller :

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);
        }

View 模型

public class RolesViewModel
{
    public IEnumerable<string> RoleNames { get; set; }
    public string UserName { get; set; }
}

View :简单的

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

关于c# - 将所有用户及其角色放入表中 asp.net mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936469/

相关文章:

c# - FileStream 保存文件然后立即在 .NET 中解锁?

jquery提交-在发布之前更改输入值

c# - MVC 重定向结果

c# - 带有 LEFT JOIN 条件子查询的 LINQ 查询

c# - VSTO 自定义 Outlook 文件夹上下文菜单

C# 应用程序 - 我应该使用存储过程还是 ADO.NET 和 C# 编程技术?

javascript - 如何在 SQL Server 2012 中使用 Soap Jquery 保存数据?

ASP.NET MVC 对象在 post 方法中丢失

c# - 在派生的 C# 类中隐藏属性

asp.net - 如何将 MVC 帐户 Controller 添加到 Visual Studio 2013 中的 WebApi 项目?