asp.net MVC3 razor:根据用户角色显示操作链接 [英] asp.net MVC3 razor: display actionlink based on user role

查看:31
本文介绍了asp.net MVC3 razor:根据用户角色显示操作链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 MVC 的新手.我希望能够为某些用户隐藏一些操作链接.假设我有一个创建"操作链接,我只希望管理员查看并单击它.我想使用 asp.net 中提供的某种loggedintemplate",但它似乎在 razor 中不起作用.

I'm new to MVC. I want to be able to hide some actionlinks for some users. Say I have a "create" actionlink which I only want administrators to see and click. I want to use some sort of "loggedintemplate" available in asp.net, but it doesn't seem to work in razor.

我可以使用某种代码块和 if 语句检查当前用户及其角色,但这可能不是最佳实践?

I could use some sort of code block with an if statement checking the current user and her role, however that may not be best practice?

我的 index.cshtml..

my index.cshtml..

// want some adminauth attribute here...
@Html.ActionLink("Create New", "Create")

我的控制器..

// GET: /Speaker/Create
[Authorize(Roles = "Administrators")]
public ActionResult Create()
{
    return View();
}

推荐答案

我过去创建了一个辅助函数,仅在满足以下条件时才返回输出:

I have in the past created a helper function to only return output when a criteria is met like this:

public static MvcHtmlString If(this MvcHtmlString value, bool evaluation)
{
     return evaluation ? value : MvcHtmlString.Empty;
}

所以你可以使用这个:

@Html.ActionLink("Create New", "Create").If(User.IsInRole("Administrators"))

这样清晰易读

这篇关于asp.net MVC3 razor:根据用户角色显示操作链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆