问题描述
我试图在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: String.Join
这篇关于加载MVC5剃须刀中每个用户的角色列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!