Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.</strong></p> <p>The way the <code>IsMvcAjaxRequest</code> extension method currently works is that it checks <code>Request["__MVCASYNCPOST"] == "true"</code>, and it only works when the method is a HTTP POST request.</p> <p>If you are making HTTP POST requests throug jQuery you could dynamically insert the <code>__MVCASYNCPOST</code> value into your request and then you could take advantage of the <code>IsMvcAjaxRequest</code> extension method.</p> <p>Here is a <a href="http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266442&amp;changeSetId=17272" rel="nofollow noreferrer">link to the source of the IsMvcAjaxRequest extension method</a> for your convenience.</p> <p>Alternatively, you could create a clone of the <code>IsMvcAjaxRequest</code> extension method called <code>IsjQueryAjaxRequest</code> that checks <code>Request["__JQUERYASYNCPOST"] == "true"</code> and you could dynamically insert that value into the HTTP POST.</p> <p><strong>Update</strong></p> <p>I decided to go ahead and give this a shot here is what I came up with.</p> <p>Extension Method</p> <pre><code>public static class HttpRequestBaseExtensions { public static bool IsjQueryAjaxRequest(this HttpRequestBase request) { if (request == null) throw new ArgumentNullException("request"); return request["__JQUERYASYNCPOST"] == "true"; } } </code></pre> <p>Checking from an action if a method is a jQuery $.ajax() request:</p> <pre><code>if (Request.IsjQueryAjaxRequest()) //some code here </code></pre> <p>JavaScript</p> <pre><code>$('form input[type=submit]').click(function(evt) { //intercept submit button and use AJAX instead evt.preventDefault(); $.ajax( { type: "POST", url: "&lt;%= Url.Action("Create") %&gt;", dataType: "json", data: { "__JQUERYASYNCPOST": "true" }, success: function(data) {alert(':)');}, error: function(res, textStatus, errorThrown) {alert(':(');} } ); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload