AjaxOptions.HttpMethod =在method = POST中获取结果

时间:2018-09-03 12:04:38

标签: asp.net ajax asp.net-mvc asp.net-mvc-5 asp.net-ajax

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

1 个答案:

答案 0 :(得分:0)

@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请求的参数,因此它像POST一样使用默认的@Html.BeginForm()请求,因此它也写{{1}如果在客户端禁用了非干扰性的AJAX脚本,则为默认表单方法。

method="post"属性的目的是在启用非侵入性AJAX时覆盖默认的提交请求行为,因为其值由AjaxOptions.HttpMethod属性设置,并由非侵入性AJAX库中的data-ajax-method方法检查(请参见脚本的完整版本here):

asyncRequest()

注意:您可以看到与this referencefunction 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); } }); 的每个属性相对应的属性列表。