Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc: how to detect when a page is called using ajax

how to detect when a page is called using ajax in asp.net mvc ?

like image 364
Omu Avatar asked Jan 18 '10 15:01

Omu


4 Answers

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.

like image 58
Richard Downer Avatar answered Nov 09 '22 01:11

Richard Downer


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();
like image 40
Seb Nilsson Avatar answered Nov 09 '22 01:11

Seb Nilsson


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.

like image 5
Oded Avatar answered Nov 09 '22 01:11

Oded


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.

like image 4
Amin Emami Avatar answered Nov 09 '22 01:11

Amin Emami