How to hide action link if user has no rights to action?

后端 未结 2 975
猫巷女王i
猫巷女王i 2020-12-08 23:57
@if (Roles.IsUserInRole(\"Administrators\"))
{
  
  • @Html.ActionLink(\"Create New\", \"Create\")
  • }

    I have bounch of roles for use

    2条回答
    •  暗喜
      暗喜 (楼主)
      2020-12-09 00:25

      I would write a custom action link helper:

      public static class LinkExtensions
      {
          public static IHtmlString ActionLinkIfInRole(
              this HtmlHelper htmlHelper, 
              string roles,
              string linkText, 
              string action
          )
          {
              if (!Roles.IsUserInRole(roles))
              {
                  return MvcHtmlString.Empty;
              }
              return htmlHelper.ActionLink(linkText, action);
          }
      }
      

      and then in my views:

      @Html.ActionLinkIfInRole("Administrators", "Create New", "Create")
      

    提交回复
    热议问题