3

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);
        }
    }
1

2 Answers 2

4

Check the user agent, as this:

var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest"
           || Request.Headers["X-Requested-With"] == "Fetch";
Sign up to request clarification or add additional context in comments.

2 Comments

Also an example(aspnet/security source code) is here github.com/aspnet/Security/blob/…
IsAjaxRequest() in MVC internally use this to check for AJAX calls. So, I don't think this as an alternative.
3

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.