2015-09-04 63 views
1

我正在使用MVC内置的用户角色数据库在我的应用程序中处理角色。我想在我看来以列表格式显示所有用户。到目前为止,我得到了列表我的表中的角色,但我无法得到用户反对。获取用户对实体框架中的角色6

我的控制器代码:

[HttpGet] 
[AllowAnonymous] 
public ActionResult Roles() 
{ 
    var ro = (from rl in context.Roles 
       select new { Name = rl.Name, Id = rl.Id }).ToList(). 
       Select(x => new rolesViewModel { S2 = x.Name, S1 = context.Users.Where(o => o.Roles.Any(h => h.RoleId == x.Id))}).ToList(); 

    ViewBag.Roles = ro; 
    return View("rolesList"); 
} 

在我看来,我使用IEnumerable的显示的角色用户对他们的名单。角色显示,但我真的找不到方法来显示列表用户

<table class="table"> 
    <tr> 
     <th> 
      Role 
     </th> 
     <th> 
      Assigned Users 
     </th> 

    </tr> 
    @{ 
     var s = (IEnumerable<rolesViewModel>)ViewBag.Roles; 
    } 
    @foreach (var t in s) 
    { 
     <tr> 
      <td>@t.S2</td> 
      <td>@t.S1</td> 
     </tr> 

    } 

</table> 

回答

0

你可以使用内置的成员资格/角色功能,在您的视图:

@{ 
string[] rls = Roles.GetAllRoles(); 
    foreach (string r in rls) 
    { 
     string[] usrs = Roles.GetUsersInRole(r); 
     foreach (string u in usrs) 
     { 
     <text> 
     <tr> 
      <td>@u</td> 
     </tr> 
     </text> 
     } 
    } 
} 
0

如果您使用的身份,你可以通过使用用户管理和角色管理器列表中的角色的角色和用户:

public ActionResult Roles() 
{ 
    var rolemanager = new RoleManager<IdentityRole>(
     // imaging you are using default IdentityRole and RoleStore 
     // otherwise use own 
     new RoleStore<IdentityRole>(
      // imaging your EF context name id ApplicationDbContext 
      HttpContext.GetOwinContext().Get<ApplicationDbContext>())); 

    var userManager = HttpContext.GetOwinContext() 
     .GetUserManager<UserManager<ApplicationUser>>(); 

    var rolesWithUsers = rolemanager.Roles.Select(r => 
     new RoleViewModel 
     { 
      Name = r.Name, 
      Users = r.Users.Select(u => userManager.FindById(u.UserId).UserName) 
     }); 

    return View(rolesWithUsers,"rolesList"); 
} 

现在,在你看来,你可以写这样的事情:

@model IEnumerable<Mynamespace.RoleViewModel> 
// table header 

@foreach(var item in Model) 
{ 
    <tr> 
     <td>@item.Name</td> 
     <td>@string.Join(", ", item.Users)</td> 
    </tr> 
} 

public class RoleViewModel 
{ 
    public string Name {get; set;} 
    public IEnumerable<string> Users {get; set; } 
}