Is there any attribute relating to AJAX to be set for ASP.NET MVC controller actions?

后端 未结 6 910
轻奢々
轻奢々 2020-11-30 02:13

I want to use partial views with AJAX calls in ASP.NET MVC, and this is the first time I\'m using it. I just searched to see if there is anything special I should know befor

6条回答
  •  余生分开走
    2020-11-30 03:02

    For those looking for a .NET Core solution it's a little bit more involved, as IsAjaxRequest() is no longer available.

    Below is the code I've used in production on several projects to great effect.

    public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
    {
      public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor actionDescriptor)
      {
        if(routeContext.HttpContext.Request.Headers != null &&
          routeContext.HttpContext.Request.Headers.ContainsKey("X-Requested-With") &&
          routeContext.HttpContext.Request.Headers.TryGetValue("X-Requested-With", out StringValues requestedWithHeader))
        {
          if(requestedWithHeader.Contains("XMLHttpRequest"))
          {
            return true;
          }
        }
    
        return false;
      }
    }
    

提交回复
热议问题