AjaxOptions.HttpMethod = GET导致method = POST

问题描述 投票:0回答:1

我有以下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"的目的是什么?

asp.net ajax asp.net-mvc asp.net-mvc-5 asp.net-ajax
1个回答
0
投票

@Ajax.BeginForm()助手使用jQuery不引人注目的AJAX库。如果检查辅助返回类型,它将返回System.Web.Mvc.Html.MvcForm,与@Html.BeginForm()相同的返回类型,它创建<form>标记:

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

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

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

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中看到与this reference的每个属性相对应的属性列表。

© www.soinside.com 2019 - 2024. All rights reserved.