asp.net MVC3 razor: display actionlink based on user role

后端 未结 6 1085
臣服心动
臣服心动 2020-11-30 18:57

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 u

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 19:26

    The solution suggested by Richard is really beautiful, though as Matthieu noted someone might need extra html code to be rendered (or not rendered) as well. Thus Matthieu's solution seems to be more widely applicable, I would just centralize the logic regarding which users are considered admins in extension method.

    Extension method:

    public static bool IsAdmin(this WebViewPage page)
    {
        return page.User.IsInRole(@"Domain\ProjectAdmins");
    }
    

    Usage:

    @if (this.IsAdmin())
    {
        

    @Html.ActionLink("Create New Version", "Create")

    }

提交回复
热议问题