views:

66

answers:

2

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

+5  A: 

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 AUJAX 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.

RedFilter
@RedFilter ok, so how do I check this header in asp.net ?
Omu
@Omu: `Request.Headers["X-Requested-With"]` or similar. Check MSDN. Headers are **always** related to requests.
Robert Koritnik
+4  A: 

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.

BuildStarted
@BuildStarted I need this check in Global.asax.cs so this won't help me
Omu
@Omu: Depends on which event of the global.asax.cs. This bool property does the same thing internally that RedFiler suggested. And do mind that headers are **always related to requests**.
Robert Koritnik
`IsAjaxRequest` is an extension to `HttpRequestBase` so it should be available everywhere that the `Request` is available.
BuildStarted
@BuildStarted is not available in Application_Error
Omu
Your sure? Did you try using HttpContext.Current.Request?
Guilherme Oenning
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.
BuildStarted