在网站上获取角色名称

时间:2016-01-09 12:51:34

标签: c# asp.net-mvc identity

我试图在我的网站上显示用户个人资料。

例如:"排名:所有者" 但我不知道如何显示等级名称。这是我目前的代码:

<p>@if (Model.Roles.Any() != false)
             {

             <b>@Model.Roles.Any()</b>

             }
             else
             {
                 <b>Member</b>
             }
    </p>

但这只会给我这个:

System.Collections.Generic.List`1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole]

那么我需要什么才能获得我的角色名称?

2 个答案:

答案 0 :(得分:0)

首先,@ Model.Roles是IdentityUserRole类型的列表。因此,如果您希望从该集合中看到某些内容,则必须对其进行迭代。

// this will never generate readable output, it will always print something like this: System.Collections.Generic.List`1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole]
<b>@Model.Roles</b>

第二:类型IdentityUserRole不包含任何包含角色名称的属性。只有roleid和userid。我认为你必须从其他地方获得那些

<强> Get Role name in IdentityUserRole 2.0 in ASP.NET

答案 1 :(得分:0)

试试此代码

public static class Extension
{
   public static string GetRoleList(this List<Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole> roles)
   {
      string rolelist="";
      if(roles.Count==0)
         return "None";
      foreach (var item in roles)
      {
         rolelist+=item+",";
      }
      return rolelist.TrimEnd(',');
   }
}

然后在视图中将其用作

<b>@Model.Roles.GetRoleList()</b>