115

anybody how can I know if the request is ajax ? (I'm using jquery for ajax)

1
  • 2
    You could also use Fiddler to watch the requests. You will learn a lot by doing this. Commented Oct 5, 2010 at 16:14

3 Answers 3

186

There's also the Request.IsAjaxRequest if you're using a later version of MVC. I don't have version 1 anymore so I can't say if it's in version 1.

If you need this check in Global.asax.cs try this: new HttpRequestWrapper(Request).IsAjaxRequest()

Sign up to request clarification or add additional context in comments.

8 Comments

@BuildStarted I need this check in Global.asax.cs so this won't help me
@BuildStarted is not available in Application_Error
Yeah, you're right. It's because it's outside of MVC and doesn't utilize HttpRequestBase. I haven't had a need for that so I didn't look too deeply. Thanks for the heads up.
new HttpRequestWrapper(Request).IsAjaxRequest();
BTW: If you are inside custom authorization filter use this to get IsAjaxRequest method on Request: filterContext.HttpContext.Request.IsAjaxRequest
|
74

All AJAX calls made by jQuery will have a header added to indicate it is AJAX. The header to check is X-Requested-With, and the value will be XMLHttpRequest when it is an AJAX call.

Note that AJAX requests are normal GETs or POSTs, so unless you (or your AJAX library like jQuery) are adding an additional header in the request, there is no way to know for certain whether it is AJAX or not.

1 Comment

@Omu: Request.Headers["X-Requested-With"] or similar. Check MSDN. Headers are always related to requests.
50

It works for me in ASP.NET MVC 3

if (Request.IsAjaxRequest())
{
     // ajax request handled
}

3 Comments

This is not available in Application_Error
This is not available in Application_BeginRequest
In Global.asax: new HttpRequestWrapper(Request).IsAjaxRequest()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.