【问题标题】:Get Role with Description for selected User获取所选用户的角色和描述
【发布时间】:2017-12-12 16:58:05
【问题描述】:
我是 MVC 的新手。我有一个带有 ViewModel 的详细信息视图,用于显示选定用户的数据。我想列出用户拥有的角色,我还想要角色的描述和角色的 ID。
我可以通过以下方式获取所选 ApplicationUser 的角色:
model.UserRoles = await _userManager.GetRolesAsync(model.AppUser);
我不知道如何获取每个角色的描述并将其显示在我的详细信息视图中。
提前致谢。
【问题讨论】:
标签:
asp.net-mvc
asp.net-identity
【解决方案1】:
我想通了。我希望这对某人有所帮助。我不知道这是否是最好或最有效的方法,但它正在工作。我获得了以下用户角色:
//Get the User Roles
IList<String> userRoles = await _userManager.GetRolesAsync(model.AppUser);
我用它来获取角色描述:
List<String> roleDescription = new List<String>();
if (userRoles.Count > 0)
{
foreach (string r in userRoles)
{
//Get the Description for the assigned Role
var desc = _roleManager.Roles.Where(n => n.Name == r).Select(d => d.Description).Single();
roleDescription.Add(desc.ToString());
}
//Using Tuple to combine text in [Role] | [Description] format in View
var roleWithDesc = new List<Tuple<string, string>>();
for (int i = 0; i < userRoles.Count; i++)
{
roleWithDesc.Add(Tuple.Create(userRoles[i].ToString(), roleDescription[i].ToString()));
}
model.UserRoles = roleWithDesc;
}
这是我的 ViewModel 中的代码:
public ApplicationUser AppUser { get; set; }
public Employee Employee { get; set; }
[Display(Name = "User Roles")]
public List<Tuple<string, string>> UserRoles { get; set; }
[Display(Name = "Available Roles")]
public List<Tuple<string, string>> AllRoles { get; set; }