Ajax.BeginForm总是在执行' POST'

时间:2015-02-24 14:30:45

标签: jquery ajax asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有两个ajax表单:

@using (Ajax.BeginForm("Index2","Home", 
    new AjaxOptions
        {
            UpdateTargetId = "result", 
            HttpMethod = "PUT"
        }, 
    new
        {
            onclick = "Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));",
            onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, httpMethod: 'PUT', updateTargetId: 'result' });"
        }))
{
    <input type="hidden" name="id" value='1'/>
    <input type="submit" value="OK Put" />
}

@using (Ajax.BeginForm("Index2","Home", 
    new AjaxOptions
        {
            UpdateTargetId = "result", 
            HttpMethod = "DELETE"
        }, 
    new
        {
            onclick = "Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));",
            onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, httpMethod: 'DELETE', updateTargetId: 'result' });"
        }))
{
    <input type="hidden" name="id" value='1'/>
    <input type="submit" value="Error Delete" />
}

在第一个中,我正在使用PUT而第二个是DELETE,但在fiddler中,它总是POST

要继续测试,我添加了一个代码(此代码仅包含测试提案)

(function () {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (a) {
        console.log("~>" + a);
    //console.log(this);
    var x = a;
    this.addEventListener('load', function () {
        //console.log(this);
        if(x == "POST"){
                 alert("Was a POST");
            }
        });
        origOpen.apply(this, arguments);
    };
})();

为什么我的其他HttpVerbs总是被视为POST

2 个答案:

答案 0 :(得分:2)

docs看来,GET和POST只有HttpMethod属性支持的两个动词:

  

获取或设置HTTP请求方法(&#34; Get&#34;或&#34; Post&#34;)。

所以可能发生的是你正在使用的PUT或DELETE不被接受,并且属性默认为POST:

  

HTTP请求方法。默认值为&#34; Post&#34;。

答案 1 :(得分:0)

一种解决方法是在Ajax.BeginForm的OnBegin处“覆盖” HTTP方法:

首先在OnBegin处调用JavaScript函数集

@using (Ajax.BeginForm("", "", null, new AjaxOptions()
    {                   
        OnBegin = "beginSubmit",
        ...

然后-在JavaScript函数中-将请求类型更改为PUT

<script type="text/javascript">
    function beginSubmit(xhr, o) {
        o.type = "PUT";
    }
</script>