【问题标题】:Continually receiving 400 (Bad Request) on jquery ajax post to MVC controller在 jquery ajax 发布到 MVC 控制器时不断收到 400(错误请求)
【发布时间】:2013-01-11 15:40:26
【问题描述】:

我的 ajax 调用看起来像这样

$.ajax({ //actually approve or reject the promotion
                url: url,
                type: "POST",
                data: '{'+data.PromotionId+','+data.UserId+','+data.ReasonText+'}',
                dataType: "json",
                //contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (indicator == 'A') {
                        alert('Promotion approved successfully!');
                    }
                    else {
                        alert('Promotion rejected successfully.');
                    }

                    var homelink = '<%: Url.Action("Index","Home") %>';
                    window.location.href = (homelink);


                    returndata = data;
                },
                error: function (xhRequest, ErrorText, thrownError) {
                    alert("Failed to process promotion correctly, please try again");
                    console.log('xhRequest: ' + xhRequest + "\n");
                    console.log('ErrorText: ' + ErrorText + "\n");
                    console.log('thrownError: ' + thrownError + "\n");
                }
            });

我的 MVC 控制器如下所示:

 [HttpPost]
    public HttpResponseMessage ApprovePromotion(PromotionDecision decision)
    {
        if (ModelState.IsValid && decision != null)
        {
            bool status = PromotionBo.ApprovePromotion(decision);
            if (status == true)
                return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }

我曾认为这两种语法都是正确的,但是每次我进行 ajax 调用时都会收到 400 响应。我到底做错了什么?

【问题讨论】:

    标签: jquery post asp.net-mvc-4


    【解决方案1】:

    您正在向服务器发送一个完全损坏且无效的 JSON 字符串。控制器操作拒绝它是正常的。除此之外,您已将 contentType 参数放入 cmets 中,指定您要发送 JSON 请求。

    所以这是执行请求的正确方法:

    $.ajax({ //actually approve or reject the promotion
        url: url,
        type: "POST",
        data: JSON.stringify({ 
            // Those property names must match the property names of your PromotionDecision  view model
            promotionId: data.PromotionId, 
            userId: data.UserId, 
            reasonText: data.ReasonText
        }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (indicator == 'A') {
                alert('Promotion approved successfully!');
            }
            else {
                alert('Promotion rejected successfully.');
            }
    
            var homelink = '<%: Url.Action("Index","Home") %>';
            window.location.href = (homelink);
    
            returndata = data;
        },
        error: function (xhRequest, ErrorText, thrownError) {
            alert("Failed to process promotion correctly, please try again");
            console.log('xhRequest: ' + xhRequest + "\n");
            console.log('ErrorText: ' + ErrorText + "\n");
            console.log('thrownError: ' + thrownError + "\n");
        }
    });
    

    请注意我是如何使用现代浏览器原生内置的 JSON.stringify 方法来确保发送到服务器的 JSON 正确且所有值都正确编码。如果您需要支持石器时代的浏览器,您可以在页面中包含json2.js 脚本,该脚本将定义JSON.stringify 方法。

    重要提示:绝对不会在您的代码中使用字符串连接构建 JSON 字符串。

    或者,如果您不想发送 JSON 请求,您可以发送标准 application/x-www-form-urlencoded 请求:

    $.ajax({ //actually approve or reject the promotion
        url: url,
        type: "POST",
        data: { 
            promotionId: data.PromotionId, 
            userId: data.UserId, 
            reasonText: data.ReasonText
        },
        success: function (data) {
            if (indicator == 'A') {
                alert('Promotion approved successfully!');
            }
            else {
                alert('Promotion rejected successfully.');
            }
    
            var homelink = '<%: Url.Action("Index","Home") %>';
            window.location.href = (homelink);
    
            returndata = data;
        },
        error: function (xhRequest, ErrorText, thrownError) {
            alert("Failed to process promotion correctly, please try again");
            console.log('xhRequest: ' + xhRequest + "\n");
            console.log('ErrorText: ' + ErrorText + "\n");
            console.log('thrownError: ' + thrownError + "\n");
        }
    });
    

    这应该以相同的方式工作,并且控制器操作应该能够正确绑定模型。

    备注:我注意到您在成功回调中使用了以下行:returndata = data;。这使我相信您以某种方式尝试在成功回调之外使用异步 AJAX 请求的结果,这是不可能的。我不知道你在用这个 returndata 变量做什么,但我觉得它是错误的。

    【讨论】:

    • 是的,我认为它以某种方式被破坏了,上面的代码是在你连续工作两个小时并且越来越沮丧之后发生的。我会试一试,并在它起作用时将其标记为答案。
    • 效果很好,感谢您提供的有用且内容丰富的回答。
    【解决方案2】:

    [ValidateAntiForgeryToken] 属性用于MVC 操作方法并结合Ajax 调用时也会出现此错误。

    看看这个,可能也有帮助: https://stackoverflow.com/a/60952294/315528

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多