且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在jquery ajax帖子上不断收到400(Bad Request)到MVC控制器

更新时间:2023-01-03 18:28:44

您正在向服务器发送完全损坏且无效的JSON字符串。控制器动作拒绝它是正常的。除此之外,您还要注释 contentType 参数,指定您要发送JSON请求。

You are sending a completely broken and invalid JSON string to the server. It's normal that the controller action rejects it. In addition to that you have put into comments the contentType parameter specifying that you want to send a JSON request.

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

So here's the correct way to do the request:

$.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 方法。

Notice how I am using the JSON.stringify method that is natively built-into modern browsers to ensure that the JSON being sent to the server is correctly and all values are properly encoded. And if you need to support browsers from the stone age, you could include the json2.js script to your page which will define the JSON.stringify method.

重要说明:绝对不会使用字符串连接来构建JSON字符串,如代码中所示。

Important remark: Absolutely never build JSON strings using string concatenations as in your code.

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

Alternatively if you don't want to send a JSON request you could send a standard application/x-www-form-urlencoded request:

$.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");
    }
});

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

This should work the same way and the controller action should be able to properly bind the model.

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

Remark: I have noticed that you used the following line in your success callback: returndata = data;. This leads me to believe that you are somehow attempting to consume the result of an asynchronous AJAX request outside of the success callback which is not possible. I have no idea what you are doing with this returndata variable but I feel it is wrong.