2

I am trying to run this example Rendering Partial Views using ajax, but i got the following compilation error:

'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found.

    public ActionResult ItemsList(string ID)
    {
        Item item = Service.GetItemById(ID);

        if (Request.IsAjaxRequest())
        {
            return PartialView("viewPath", item);
        }
        else
        {
            return View("viewPath", item);
        }
    }
Community
  • 1
  • 1
  • I found this similar question http://stackoverflow.com/questions/18012983/request-isajaxrequest-method-not-found-in-mvc4-when-using-aspx-engine, but no answer is given – Mariyan Marinov Mar 31 '17 at 10:40

2 Answers2

3

Check the user agent, as this:

var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • Also an example(aspnet/security source code) is here https://github.com/aspnet/Security/blob/22d2fe99c6fd9806b36025399a217a3a8b4e50f4/src/Microsoft.AspNetCore.Authentication.Cookies/Events/CookieAuthenticationEvents.cs#L104 – adem caglin Mar 31 '17 at 13:50
  • `IsAjaxRequest()` in MVC internally use this to check for `AJAX` calls. So, I don't think this as an alternative. – Voodoo May 30 '19 at 12:40
1

Ricardo Peres's answer works for ajax requests but misses the new Fetch types. This works for me:

internal static class RequestHelpers
{
    internal static bool IsAjaxRequest(this HttpRequest request)
    {
        return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
            string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
            string.Equals(request.Headers["X-Requested-With"], "Fetch", StringComparison.Ordinal);
    }
}
Brian
  • 395
  • 1
  • 3
  • 14