Here i need to list the current user roles, for example if i have many roles, like admin,operator,editor,writer etc and one user name(userone) is in tow roles how i will be able to list the roles like :
在这里,我需要列出当前的用户角色,例如,如果我有很多角色,如管理员,操作员,编辑器,编写器等,并且一个用户名(userone)处于两个角色,我将能够列出如下角色:
user name : userone
roles : editor,writer
for that i found this code but is there any simple or better to do:
因为我找到了这个代码,但有任何简单或更好的做法:
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 + ",";
}
for sure in view you need to call the ViewBag.selectedRoleName
肯定在视图中你需要调用ViewBag.selectedRoleName
so here if see there is (,) extra in last role name , just searching better way to do it thanks in advance
所以在这里,如果看到最后一个角色名称中有(,)额外的,只需要提前感谢更好的方式来做到这一点
0
Here is View:
这是视图:
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);
}
}
And here is view:
以下是观点:
@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>
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2016/12/05/35ba7c8f2f004667ed637f9ca8f3eadd.html。