我想在ASP.NET MVC5中显示我的用户列表,在列中我想显示用户拥有的每个角色(以逗号分隔)。
所以我有一个简单的UserViewModel:
public class UserViewModel
{
public string UserName { get; set; }
public string Email { get; set; }
public string AdatlapNev { get; set; }
public string Roles { get; set; }
}
在我的视图中,模型为:@model IEnumerable<UserViewModel>
问题在于显示角色。我试着这样做:
public ActionResult UserList()
{
return View(db.Users.Select(u => new UserViewModel
{
AdatlapNev = u.Adatlap == null ? "NULL" : u.Adatlap.Nev,
Email = u.Email,
UserName = u.UserName,
Roles = u.Roles.Select(r => db.Roles.Find(r.RoleId).Name).Aggregate((s1, s2) => s1 + ", " + s2)
}
));
}
但它不起作用。我得到System.ArgumentException
,表示我无法在此处使用Find
方法。
感谢您的帮助!
答案 0 :(得分:2)
您需要一个RoleManager来获取名称:
public ActionResult UserList()
{
var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
return View(
db.Users.Select(u => new UserViewModel
{
AdatlapNev = u.Adatlap == null ? "NULL" : u.Adatlap.Nev,
Email = u.Email,
UserName = u.UserName,
Roles = String.Join(", ", u.Roles.Select(r => rm.FindById(r.RoleId).Name))
})
);
}
答案 1 :(得分:0)
尝试
db.Roles.Where(x => u.Roles.Any(y => x == y.RoleId)).Select(x => x.Name)
而不是
u.Roles.Select(r => db.Roles.Find(r.RoleId).Name)
答案 2 :(得分:0)
我找到了一个有效的解决方案。
// GET: Admin/UserList
public ActionResult UserList()
{
var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
var q = db.Users.Select(u => new
{
AdatlapNev = u.Adatlap == null ? "NULL" : u.Adatlap.Nev,
Email = u.Email,
UserName = u.UserName,
Roles = u.Roles.Select(r => r.RoleId)
});
var roles = db.Roles.Select(r => new { Id = r.Id, Name = r.Name }).ToList();
return View(q.AsEnumerable().Select(x => new UserViewModel
{
AdatlapNev = x.AdatlapNev,
Email = x.Email,
UserName = x.UserName,
Roles = String.Join(", ", x.Roles.Select(j => roles.Where(r => r.Id == j).Single().Name))
}));
}