加载MVC5剃须刀中每个用户的角色列表 [英] Load list of roles for each user in MVC5 razor

查看:93
本文介绍了加载MVC5剃须刀中每个用户的角色列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ASP.net MVC应用程序中显示每个用户及其角色的行.

I am trying to display a row of each user and their roles in the ASP.net MVC application.

用户及其角色存储在ASP.net成员资格提供程序表中. 使用下面的代码,我可以显示每个用户及其分配的角色,但是我的问题是,如果该用户具有多个角色,则该用户将被重复使用.

Users and their roles are stored in ASP.net membership provider table. Using the code below I can display each user and the role they are assigned, but my problem is if the user is in multiple roles then the user gets repeated.

我尝试将UserRole设置为列表,但是由于不知道如何在下面的代码中将角​​色添加到列表中,我现在陷入困境.您能给我一些方向吗?

I tried making UserRole as List but I am now stuck as I do not know how to add the roles to a list in the code below. Could you please provide me some direction?

我的视图模型是:

public class UserViewModel
{
   public string UserName { get; set; }
   public List<String> UserRole { get; set; }
}


var roles = ApplicationRoles.RolesList;
       var users = new List<UserViewModel>();
       foreach (var role in roles)
        {
           foreach (var user in Roles.GetUsersInRole(role)) 
            {
               users.Add(new UserViewModel {UserName = user, UserRole = role });
            }
        }

return View(users);

如何加载角色,以便在用户具有多个角色的情况下不重复用户名?

How can I load the roles so I do not repeat username if the user has multiple roles attached to him/her?

我想以以下格式显示它:

I would like to display it in the following format:

======================

=======================

用户|角色

约翰|管理员,批准人

山姆|批准人

======================

=======================

推荐答案

您为什么不喜欢

  foreach (var user in Roles.GetUsersInRole(role)) 
  {
      users.Add(new UserViewModel {UserName = user, NameAndRole = user + "|"+ String.Join(",", UserRole.ToArray() });
  }

或者您可以在viewmodel类中添加属性并使用

or you can add property in your viewmodel class and use it

Public String NameAndRole
{
  get
   { return name + " | "+ String.Join(",", UserRole.ToArray()) }
}

MSDN: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆