简体   繁体   English

列表asp.net标识中用户的角色名称

[英]role names for user in list asp.net identity

I am trying to list all my users in view. 我想在视图中列出我的所有用户。 I also want to list roles which is belong to user. 我还想列出属于用户的角色。 But i just can get id of role for user. 但我只能为用户获得角色的身份。 But I want to list all my role names not role id. 但我想列出我的所有角色名称而不是角色ID。 How can i do that? 我怎样才能做到这一点? Here is my code: 这是我的代码:

public async Task<ActionResult> Index()
{
    var user = await _context.Users.Include(x=> x.Roles).ToListAsync();
    ViewBag.Roles = await _context.Roles.ToListAsync();
    return View(user);
}

In view 在视野中

@model List<Projectname.Web.Models.ApplicationUser>

@foreach (var c in Model) 
{
    <tr>
        <td>@c.UserName</td>
        <td>@c.Email</td>
        <td>@c.LockoutEnabled</td>
        @foreach (var role in c.Roles)
        {
            <td>@role.RoleId</td>
        }
    </tr>
}

ps I am using Asp.net identity ps我使用的是Asp.net身份

If you are trying to get the roles of each user, Aren't you supposed to just access it from your var user ? 如果您正在尝试获取每个用户的角色,您是否应该只是从您的var user访问它? In other words, you just need to use user.Roles 换句话说,您只需要使用user.Roles

Since you already fetched a list of user under the variable named user ... Well first of all if you are saving a list, array or whatever form of collection, you have to name your variable in plural form. 因为您已经在名为user的变量下获取了一个用户列表...首先,如果要保存列表,数组或任何形式的集合,则必须以复数形式命名变量。 In your case it should look like: 在你的情况下,它应该看起来像:

var users = await _context.Users.Include(x=> x.Roles).ToListAsync();

Now back to the main point... Now that you have fetched the users with Include of Roles, you just it would look like this, assuming that your Model is the collection of users. 现在回到主要观点......现在您已经使用Include of Roles获取了users ,只要它看起来像这样,假设您的Model是用户集合。

@foreach (var user in Model) 
{
    <tr>
        <td>@user.UserName</td>
        <td>@user.Email</td>
        <td>@user.LockoutEnabled</td>
        @foreach (var role in user.Roles)
        {
            <td>@role.Id</td>
            <td>@role.Name</td>
        }
    </tr>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM