我希望在ASP.NET MVC中显示取决于活动用户的给定角色的内容.
使用WebForms比较旧的时尚方式:
protected void Page_Load(Object sender, EventArgs e)
{
if(User.IsInRole("Administrator")) {
adminLink.Visible = true;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在使用ASP.NET MVC时,我将如何继续编写?从我的角度来看,将它直接放在视图文件中是错误的,并且为每个视图分配一个变量也不是很好.
创建Html帮助程序并在其代码中检查当前用户角色:
public static class Html
{
public static string Admin(this HtmlHelper html)
{
var user = html.ViewContext.HttpContext.User;
if (!user.IsInRole("Administrator")) {
// display nothing
return String.Empty;
// or maybe another link ?
}
var a = new TagBuilder("a");
a["href"] = "#";
a.SetInnerText("Admin");
var div = new TagBuilder("div") {
InnerHtml = a.ToString(TagRenderMode.Normal);
}
return div.ToString(TagRenderMode.Normal);
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
或者为库存Html帮助器创建包装器.ActionLink的示例(此HtmlHelper htmlHelper,字符串linkText,字符串actionName,字符串controllerName):
public static class Html
{
public static string RoleActionLink(this HtmlHelper html, string role, string linkText, string actionName, string controllerName)
{
return html.ViewContext.HttpContext.User.IsInRole(role)
? html.ActionLink(linkText, actionName, controllerName)
: String.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5166 次 |
| 最近记录: |