【发布时间】:2018-02-07 18:32:04
【问题描述】:
正如问题所说,我正在尝试在 MVC5 视图中检查用户对象的角色。基本上我的观点是列出所有注册用户及其当前角色。
这是我的看法:
@model IEnumerable<IconicMx.CandidateDatabase.Models.ApplicationUser>
@{
ViewBag.Title = "Talent Center Institute: Usuarios";
ViewBag.Menu = "Usuarios";
ViewBag.Submenu = "Lista de usuarios";
ViewBag.MenuFaClass = "fa-cog";
ViewBag.InitialPanel = true;
}
<h2>Lista de usuarios</h2>
<p>
@Html.ActionLink("Crear usuario", "Register", "Account", null, new { @class = "btn btn-primary" })
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th>
Tipo de usuario
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@if (ViewBag.manager.IsInRole(item.Id, "Admin"))
{
<text>Administrador</text>
}
else
{
<text>Capturista</text>
}
</td>
<td>
@Html.ActionLink("Editar", "Edit", new { id=item.Id }, new { @class = "btn btn-primary btn-xs" }) |
@Html.ActionLink("Eliminar", "Delete", new { id=item.Id }, new { @class = "btn btn-primary btn-xs" })
</td>
</tr>
}
</table>
这是我的控制器:
public ActionResult Index()
{
ViewBag.manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
return View(db.Users.ToList());
}
我正在尝试使用 UserManager 的 IsInRole 函数,但在渲染视图时出现运行时错误,提示该函数未定义!!如果我在控制器中调用此函数,它会按预期运行。
注意:我不是想在会话中获取当前登录的用户!! (User.identity.IsInRole 没有帮助)
【问题讨论】:
-
我认为最好将此信息放入视图模型并以这种方式将信息传递给视图,而不是尝试访问视图本身中的
IUserManager实例。分离关注点:为控制器中的视图准备数据,并与视图一起显示数据。
标签: c# asp.net-mvc asp.net-mvc-5 asp.net-identity