how to know if the request is ajax in asp.net mvc?

asp.netasp.net MvcAjax

asp.net Problem Overview


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

asp.net Solutions


Solution 1 - asp.net

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()

Solution 2 - asp.net

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.

Solution 3 - asp.net

It works for me in ASP.NET MVC 3

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmuView Question on Stackoverflow
Solution 1 - asp.netBuildstartedView Answer on Stackoverflow
Solution 2 - asp.netD'Arcy RittichView Answer on Stackoverflow
Solution 3 - asp.netPiotr CzyżView Answer on Stackoverflow