how to detect when a page is called using ajax in asp.net mvc ?
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.