AjaxOptions.HttpMethod = GET results in method=POST



我有以下AjaxOptions对象:

AjaxOptions ajaxOpts = new AjaxOptions
{        
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace
};

在视图中,我有以下形式:

@using (Ajax.BeginForm("GetPeopleData", ajaxOpts))
{
<div>            
<button type="submit">Submit</button>
</div>
}

这将生成以下 HTML:

<form action="/People/GetPeopleData" data-ajax="true" data-ajax-method="Get" id="form0" method="post">
<div>            
<button type="submit">Submit</button>
</div>
</form>

当我提交表单时,我可以看到发送了GET请求。

为什么 HTML 有data-ajax-method="Get"method="post"method="post"的目的是什么?

@Ajax.BeginForm()助手利用 jQuery 不显眼的 AJAX 库。如果检查帮助程序返回类型,它将返回System.Web.Mvc.Html.MvcForm,返回类型与创建<form>标记的@Html.BeginForm()相同:

public static MvcForm BeginForm(
this AjaxHelper ajaxHelper,
AjaxOptions ajaxOptions
)

由于它的所有重载都没有在System.Web.Mvc.FormMethod枚举中指定 HTTP 请求的参数,因此它像@Html.BeginForm()一样使用默认POST请求,因此如果在客户端禁用了不显眼的 AJAX 脚本,它还为默认表单方法编写method="post"

data-ajax-method属性的目的是在启用不显眼的 AJAX 时覆盖默认的提交请求行为,因为它的值由AjaxOptions.HttpMethod属性设置,并由不显眼的 AJAX 库中asyncRequest()方法检查(在此处查看脚本的完整版本(:

function asyncRequest(element, options) {
var confirm, loading, method, duration;
confirm = element.getAttribute("data-ajax-confirm");
if (confirm && !window.confirm(confirm)) {
return;
}
loading = $(element.getAttribute("data-ajax-loading"));
duration = parseInt(element.getAttribute("data-ajax-loading-duration"), 10) || 0;
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined, // here AJAX method is checked (GET or POST)
url: element.getAttribute("data-ajax-url") || undefined,
cache: (element.getAttribute("data-ajax-cache") || "").toLowerCase() === "true",
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(element, arguments);
if (result !== false) {
loading.show(duration);
}
return result;
},
complete: function () {
loading.hide(duration);
getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(element, arguments);
},
success: function (data, status, xhr) {
asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(element, arguments);
},
error: function () {
getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"]).apply(element, arguments);
}
});

注:您可以看到与本参考中AjaxOptions的每个属性对应的属性列表。

相关内容

最新更新