2016-12-05 87 views
2

在這裏我需要列出當前的用戶角色,例如,如果我有很多角色,如管理員,操作員,編輯器,作家等和一個用戶名(userone)在兩個角色,我將如何能夠列出的角色,如:MVC 5獲取當前用戶角色名稱

user name : userone 
roles  : editor,writer 

的,我發現這個代碼,但沒有任何簡單的或更好的事:

  UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); 
      RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));  
      string name = User.Identity.Name; 
      string id = UserManager.FindByName(name).Id; 
      IList<string> roleNames = UserManager.GetRoles(id); 
      string selectedRoleName = ""; 

      foreach (var item in roleNames) 
      { 
       ViewBag.selectedRoleName += item + ","; 
       selectedRoleName += item + ","; 
      } 

肯定鑑於你需要調用ViewBag.selectedRoleName

因此在這裏,如果看到有(,)在過去的角色名額外,只是在尋找更好的方式來做到這一點提前感謝

+0

如果要連接角色名稱,請使用'String.Join': 'string.Join(「,」,roleNames.ToArray());' – Marco

回答

0

這裏是查看:

public class UsersAdminController : Controller 
{ 
    public UsersAdminController() 
    { 
    } 

    public UsersAdminController(ApplicationUserManager userManager, ApplicationRoleManager roleManager) 
    { 
     UserManager = userManager; 
     RoleManager = roleManager; 
    } 

    private ApplicationUserManager _userManager; 
    public ApplicationUserManager UserManager 
    { 
     get 
     { 
      return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
     } 
     private set 
     { 
      _userManager = value; 
     } 
    } 

    private ApplicationRoleManager _roleManager; 
    public ApplicationRoleManager RoleManager 
    { 
     get 
     { 
      return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); 
     } 
     private set 
     { 
      _roleManager = value; 
     } 
    } 

    public async Task<ActionResult> Details(string id) 
    { 
     if (id == null) 
     { 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 
     var user = await UserManager.FindByIdAsync(id); 

     ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id); 

     return View(user); 
    } 
    } 

這裏是視圖:

@model YourApp.Models.ApplicationUser 
<div class="page-header"> 
</div> 
<div> 
<dl class="dl-horizontal"> 
<dt> 
@Html.DisplayNameFor(model => model.UserName) 
</dt> 
<dd> 
@Html.DisplayFor(model => model.UserName) 
</dd> 
</dl> 
</div> 
<table class="table"> 
@foreach (var item in ViewBag.RoleNames) 
{ 
    <tr> 
     <td> 
      @item 
     </td> 
    </tr> 
} 
</table>