【问题标题】:How create Ajax Helpers in MVC3如何在 MVC3 中创建 Ajax 助手
【发布时间】:2012-07-02 08:41:43
【问题描述】:

我在这里创建@Html.ActionLink 助手我检查用户的权限。如果是,我会显示此链接,否则不会。现在的问题是@Ajax.ActionLink 我可以为 Ajax.ActionLink 做助手吗?我制作自定义助手来检查权限。它适用于 html.actionlink 助手。我如何检查 ajax 操作中的权限?

 public static IHtmlString CustomActionLink(this HtmlHelper htmlHelper, int userId, string reqController, string reqAction,  string linkText,int reqActionId = 0)
    {

        bool isAllowed = checkPermission(userId, reqController, reqAction, reqActionId);
        if (isAllowed == false)
        {
            return MvcHtmlString.Empty;
        }
        return htmlHelper.ActionLink(linkText, reqAction, new { id =reqActionId });
    }

我想在 Ajax Actions 中进行同样的检查。

【问题讨论】:

    标签: ajax asp.net-mvc asp.net-mvc-3 authorization


    【解决方案1】:

    在 ASP.NET MVC 中,HTML 帮助器方法只是现有 HtmlHelper 和 AjaxHelper 类的 extension methods。一旦您了解了 .NET 中的扩展方法是什么以及它是如何工作的,将这个概念应用到AjaxHelper 类中就不难了:

    public static IHtmlString CustomAjaxActionLink(
        this AjaxHelper ajaxHelper, 
        AjaxOptions ajaxOptions,
        int userId, 
        string reqController, 
        string reqAction,  
        string linkText,
        int reqActionId = 0
    )
    {
        bool isAllowed = checkPermission(userId, reqController, reqAction, reqActionId);
        if (!isAllowed)
        {
            return MvcHtmlString.Empty;
        }
    
        return ajaxHelper.ActionLink(
            linkText, 
            reqAction, 
            new { id = reqActionId }, 
            ajaxOptions
        );
    }
    

    在您的视图中,只需使用这个自定义帮助器(当然,在将声明包含类的命名空间带入作用域之后):

    @Ajax.CustomAjaxActionLink(
        new AjaxOptions { UpdateTargetId = "foo" },
        123,
        "SomeController",
        "SomeAction",
        "click me and get a surprise!",
        456
    )
    

    【讨论】:

      【解决方案2】:

      使用 AuthorizeAttribute 怎么样?

      public class AuthorizeAdminAttribute : AuthorizeAttribute
          {
      
              public override void OnAuthorization(AuthorizationContext filterContext)
              {
                  if(!AppSecurity.Instance.IsUserInRoles(filterContext.HttpContext.User, AdminGroups))
                  {
                      HandleUnauthorizedRequest(filterContext);
                  }
                  base.OnAuthorization(filterContext);
              }
          }
      

      在你的控制器中你可以使用类似的东西:

      [AuthorizeAdmin]
              public ActionResult Index()
              {
                  return View();
              }
      

      【讨论】:

        猜你喜欢
        • 2012-11-26
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 2010-11-01
        • 1970-01-01
        • 2013-02-25
        • 2011-08-04
        • 1970-01-01
        相关资源
        最近更新 更多