asp.net-mvc 在 MVC Asp.net 身份中具有角色的用户列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27758990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:21:41  来源:igfitidea点击:

List of Users with roles in MVC Asp.net identity

asp.net-mvcasp.net-identityasp.net-roles

提问by Rras

I want to have list of all the users registered on my site with their roles.

我想列出在我的网站上注册的所有用户及其角色。

Id | Name | Role

身 | 姓名 | 角色



1 | ABC | Admin

1 | ABC | 行政



2 | DEF | User

2 | 防御 | 用户

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

请给出任何解决方案,谢谢

采纳答案by Imran Rashid

Create a new class called UserViewModel. This will act as a view model for your page.

创建一个名为 UserViewModel 的新类。这将充当您页面的视图模型。

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.

在控制器的 action 方法中,获取用户列表及其角色并将其映射到 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>

回答by Zahir Firasta

Although it is very late to answer this question, but here it is for the future visits:

虽然现在回答这个问题已经很晚了,但这里是为了以后的访问:

Create view model class:

创建视图模型类:

public class UserViewModel
{
    public string Username { get; set; }
    public string Email { get; set; }
    public string Role { get; set; }
}

Then populate this view model class in controller:

然后在控制器中填充这个视图模型类:

var usersWithRoles = (from user in context.Users
                      from userRole in user.Roles
                      join role in context.Roles on userRole.RoleId equals 
                      role.Id
                      select new UserViewModel()
                      {
                          Username = user.UserName,
                          Email = user.Email,
                          Role = role.Name
                      }).ToList();

Here, context.Usersrepresents the AspNetUserstable which has a navigation property Roleswhich represents the AspNetUserInRolestable. Then we perform join of context.Roleswhich represents the AspNetRolestable to get the role name.

在这里,context.Users表示AspNetUsers具有表示表的导航属性RolesAspNetUserInRoles表。然后我们执行context.Roles代表AspNetRoles表的连接以获取角色名称。

Now return this list to your Index view:

现在将此列表返回到您的索引视图:

return View(userWithRoles);

In the view show the list of users with roles:

在视图中显示具有角色的用户列表:

@model IEnumerable<MyProject.Models.UserViewModel>
<div class="row">
        <h4>Users</h4>

        @foreach (var user in Model)
        {
            <p>
                <strong>
                    @user.Username | @user.Email | @user.Role
                </strong>
            </p>
        }            
</div>

Edit: To get multiple roles of user(if assigned any)

编辑:获取用户的多个角色(如果有分配)

var usersWithRoles = (from user in _ctx.Users
                     select new
                     {
                         Username = user.UserName,
                         Email = user.Email,
                         RoleNames = (from userRole in user.Roles
                                      join role in _ctx.Roles on userRole.RoleId equals role.Id
                                      select role.Name).ToList()
                     }).ToList().Select(p => new UserViewModel()

                     {
                         Username = p.Username,
                         Email = p.Email,
                         Role = string.Join(",", p.RoleNames)
                     });

回答by Armando Baltazar

I have a solution as above.
This is a solution in MVC 6.

我有上面的解决方案。
这是 MVC 6 中的解决方案。

In AccountViewModel.cs add models

在 AccountViewModel.cs 添加模型

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 Email { get; set; }
    public string RoleName { get; set; }
}

the controller is as follows:

控制器如下:

    public ActionResult Index()
    {            
        var role = (from r in context.Roles where r.Name.Contains("Adviser") select r).FirstOrDefault();            
        var users = context.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(role.Id)).ToList();

        var userVM = users.Select(user => new UserViewModel
        {
            Username = user.UserName,
            Email = user.Email,
            RoleName = "Adviser"
       }).ToList();


        var role2 = (from r in context.Roles where r.Name.Contains("Admin") select r).FirstOrDefault();
        var admins = context.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(role2.Id)).ToList();

        var adminVM = admins.Select(user => new UserViewModel
        {
            Username = user.UserName,
            Email = user.Email,
            RoleName = "Admin"
        }).ToList();


        var model = new GroupedUserViewModel { Users = userVM, Admins = adminVM };
        return View(model); 

    }

finally the view:

最后的观点:

@model ToroCRM.Models.GroupedUserViewModel
<div class="row">
        <h4>Users</h4>
        @foreach (var user in Model.Users)
        {
            <p>
                <strong>
                    @user.Username <br />
                    @user.Email<br />
                    @user.RoleName
                </strong>
            </p>
        }
        <h4>Advisers</h4>
        @foreach (var usera in Model.Admins)
        {
            <p>
                <strong>
                    @usera.Username <br />
                    @usera.Email<br />
                    @usera.RoleName
                </strong>
            </p>
        }
</div>

回答by Ad Kahn

I also have a solution as above. This is a solution in MVC 6. the reason for this is i try the above code and faced problems. so..

我也有上面的解决方案。这是 MVC 6 中的解决方案。原因是我尝试了上面的代码并遇到了问题。所以..

lets start off Create a new class called UserViewModel. This will act as a view model for your page

让我们开始创建一个名为UserViewModel的新类。这将充当您页面的视图模型

public class UserViewModel
{
    public string Username { get; set; }
    public string Email { get; set; }
    public string RoleName { get; set; }
}

The controller is as follows:

控制器如下:

public ActionResult Index()
    { 
       List<UserViewModel> modelLst = new List<UserViewModel>();
            var role = _db.Roles.Include(x => x.Users).ToList();

            foreach (var r in role)
            {
                foreach (var u in r.Users)
                {
                    var usr = _db.Users.Find(u.UserId);
                    var obj = new UserViewModel
                    {
                        Username = usr.FullName,
                        Email = usr.Email,
                        RoleName = r.Name
                    };
                    modelLst.Add(obj);
                }

            }
     return View(modelLst); 

    }

finally the view:

最后的观点:

@model IEnumerable<ToroCRM.Models.UserViewModel>

<div class="row">
 @foreach (var r in Model.DistinctBy(x=>x.RoleName).ToList())
    {

        <h4>@r.RoleName</h4><hr />
        <table class="table">
        foreach (var user in Model.Where(x=>x.RoleName == r.RoleName))
         {
              <tr><th>@user.Username</th><td>@user.Email</td></tr> 
         }
        </table>

    }
</div>