4

I have an MVC project in which I have a form with a submit button. I have added a jquery client-side handler that intercepts the form submit event. The javascript function calls the same MVC action that would have been called without the javascript.

 $("form[action ='/List/CreateItem']").submit(
            function() {
                $.post($(this).attr("action"), $(this).serialize(), function(response) { $("#results").html(response); });
                return false;
            }
            );

In the MVC action that is called, I test for Request.IsAjaxRequest to decide whether to return a view or a JSON result. My problem is that Request.IsAjaxRequest is returning false, even though I know the call is being made from the jquery function. (I know this because if I comment out the $.post line in the jquery function and just leave the return false line, nothing happens. If I un-comment the line, the action gets executed - but it returns the view because IsAjaxRequest is false.)

Should this line cause Request.IsAjaxRequest to be true?

Grant
  • 391
  • 2
  • 5
  • 6
  • 1
    $.post *does* set `X-Requested-With` and hence `IsAjaxRequest` – Craig Stuntz Nov 09 '09 at 19:34
  • This post may solve your problem: http://www.britishdeveloper.co.uk/2010/10/aspnet-mvc-isajaxrequest-jquery.html – Tuyen Nguyen Mar 27 '13 at 20:32
  • 1
    I have seen cases where Request.IsAjaxRequest() randomly returns false when loading multiple page sections via ajax. I started adding a `partial=1` parameter to the queries and `bool partial = Request.IsAjaxRequest() || !string.IsNullOrEmpty(Request["partial"]);` in the controllers to ensure I get partial pages on ajax calls and full pages when browsed. – iCollect.it Ltd Jul 18 '13 at 09:13

4 Answers4

3

The Request.IsAjaxRequest property should reflect the existence of the X-Requested-With HTTP header. Is this header actually sent to the server? As James suggests, try to profile this with Fiddler or similar proxy server alternatives.

Asbjørn Ulsberg
  • 8,721
  • 3
  • 45
  • 61
1

Well... I apologize. I don't know what has changed, but now IsAjaxRequest is returning true. I compare the code I posted above and what is executing now and I see no difference. I repeatedly got false on this before, and now I repeatedly get true. Surely I am missing something, but I don't see it.

Grant
  • 391
  • 2
  • 5
  • 6
0

I'm not sure what the difference would be but a possible way to identify if there is one is to use an HTTP profiling tool like Fiddler (www.fiddlertool.com) and look for possible differences between the two calls.

James Alexander
  • 6,132
  • 10
  • 42
  • 56
0

Does CreateItem perform redirect? See Firefox does not preserve custom headers during Ajax request redirect: an ASP.NET MVC solution

Community
  • 1
  • 1
queen3
  • 15,333
  • 8
  • 64
  • 119