请参阅下面的 Simons 回答。我这里描述的方法在最新版本的 ASP.NET MVC 中不再需要了。
IsMvcAjaxRequest 扩展方法目前的工作方式是检查Request["__MVCASYNCPOST"] == "true",并且仅在该方法是 HTTP POST 请求时才有效。
如果您通过 jQuery 发出 HTTP POST 请求,您可以将 __MVCASYNCPOST 值动态插入到您的请求中,然后您可以利用 IsMvcAjaxRequest 扩展方法。
为了您的方便,这里是link to the source of the IsMvcAjaxRequest extension method。
或者,您可以创建 IsMvcAjaxRequest 扩展方法的克隆,称为
IsjQueryAjaxRequest 检查 Request["__JQUERYASYNCPOST"] == "true",您可以将该值动态插入 HTTP POST。
更新
我决定继续尝试,这就是我想出的。
扩展方法
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
从操作中检查方法是否为 jQuery $.ajax() 请求:
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(':(');}
}
);
});