how to detect when a page is called using ajax in asp.net mvc ?
There is no specific way to determine if the call was made by javascript or directly in the browser, as it is a regular http call.
You can add a header to your ajax call to distinguish it from other calls, or possibly add a parameter to the query string that is only used on ajax calls.
ASP.NET MVC ajax does add such a header - X-Requested-With: XMLHttpRequest
, which you can use to sniff that this is an ajax call by the mvc ajax library. However, if you are using jQuery or your own hand rolled ajax calls, this will not be set. Additionally, other clients might spoof this header (using WebClient, for example) so finding it is not a guarantee that an ajax call has been made.
The best way to check if the request is an ajax request is to check Request.IsAjaxRequest()
. It's good to know that under the hood, MVC framework checks for ajax requests in the Request Parameters OR the Request Header. The code in ASP.Net MVC source code is:
public static bool IsAjaxRequest(this HttpRequestBase request) {
if (request == null) {
throw new ArgumentNullException("request");
}
return (request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));
}
So if you want to check it mannually (which is not recommended) you have to check both.
Why does it matter? It shouldn't. Are you really trying to do content negotiation?
You would need to pass some parameter with your AJAX call - AJAX is just a GET request, no different then typing a url into the address bar and pressing enter (this is why AJAX must be guarded against cross site scripting attacks, otherwise an attacker can force people to execute AJAX commands to your site just by including the url in an image)
You can check it manually like this:
bool isAjaxRequest = request.Headers["X-Requested-With"] == "XMLHttpRequest";
Or when you're in a Controller in ASP.NET MVC, which references System.Web.Mvc you will get an extension-method on the HttpRequestBase object, which you can access within an ActionMethod like this:
bool isAjaxRequest = Request.IsAjaxRequest();
According to the Professional ASP.NET MVC 1.0 book, the MVC AJAX library will insert a form field called "X-Requested-With" with a value of "XMLHttpRequest".
You can then use an extension method in System.Web.Mvc that means you can simply call Request.IsAjaxRequest()
and get a simple true or false saying if this is an AJAX request.