Dal*_*ale 7 asp.net attributes roles asp.net-mvc-3
在MVC3网站的默认安装中,左上角会创建选项卡.我想根据当前用户是否有权访问索引ViewResult来隐藏/显示这些选项卡.ViewResult允许的角色由属性定义.有没有办法获取ViewResult的角色列表?
its*_*att 10
如果你问(抱歉,我不完全清楚)关于基于角色的HTML元素的条件显示,你可以这样做:
@if (User.IsInRole("Administrators"))
{
@Html.ActionLink("Do Some Action", "DoAction", "SomeController")
}
Run Code Online (Sandbox Code Playgroud)
如果这不是您要求的,请告诉我.
根据您的评论进行跟进:
你的问题让我感兴趣,我做了一点点探讨,发现Vivien Chevallier 在这里有一个有趣的想法,它基本上可以让你写出这样的东西:
@Html.ActionLinkAuthorized("The Privilege Zone", "ThePrivilegeZone", "Home", true)
在您的视图中,然后检查控制器操作,并呈现链接或不.
在他的控制器示例中,您有一个这样的动作:
[Authorize(Roles = "Administrator")]
public ActionResult ThePrivilegeZone()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
(我想这里的关键点是你的View不知道蹲下"管理员"并依赖扩展代码在这里做繁重的工作:
public static MvcHtmlString ActionLinkAuthorized(
this HtmlHelper htmlHelper,
string linkText, string actionName, string controllerName,
RouteValueDictionary routeValues,
IDictionary<string, object> htmlAttributes, bool showActionLinkAsDisabled)
{
if (htmlHelper.ActionAuthorized(actionName, controllerName))
{
return htmlHelper.ActionLink(
linkText,
actionName, controllerName, routeValues, htmlAttributes);
}
else
{
if (showActionLinkAsDisabled)
{
TagBuilder tagBuilder = new TagBuilder("span");
tagBuilder.InnerHtml = linkText;
return MvcHtmlString.Create(tagBuilder.ToString());
}
else
{
return MvcHtmlString.Empty;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不是在这里剪切/粘贴所有代码,而是可以查看它并查看他为此获得的示例应用程序.我认为这种方法特别有趣的是视图可以显示PrivilegeZone链接,但只知道其他东西将决定是否是这种情况.因此,假设您有新的要求只允许"管理员"或"所有者"的人员访问该链接,您可以相应地修改控制器操作,而不是触摸视图代码.有趣的想法,至少对我而言.
| 归档时间: |
|
| 查看次数: |
4362 次 |
| 最近记录: |