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

后端 未结 6 1087
臣服心动
臣服心动 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:33

    You can add a function to App_Code/ViewFunctions.cshtml (create if missing)

    @using System.Web.Mvc;
    @functions{
    public static object ConditionalActionLink(object actionLink, ICollection arrAuthUsers)
    {
        bool objIsVisible = arrAuthUsers
            .Select(s => User.IsInRole(s))
            .Where(s => s.Equals(true))
            .Any();
    
        return (objIsVisible)
            ? actionLink
            : MvcHtmlString.Empty;
    }
    

    To use that function just add following code to the view.

    @ViewFunctions.ConditionalActionLink(
    @Html.ActionLink("TextToDisplay", "SomeAction", new { Area = "SomeArea", Controller = "SomeController" }), 
    new string[] { "administrator","jDoe", "someOtherUser" })
    

提交回复
热议问题