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