在jquery ajax帖子上不断收到400(Bad Request)到MVC控制器 [英] Continually receiving 400 (Bad Request) on jquery ajax post to MVC controller

查看:80
本文介绍了在jquery ajax帖子上不断收到400(Bad Request)到MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ajax电话看起来像这样

My ajax call looks like this

$.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控制器如下所示:

And my MVC controller looks like this:

 [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响应。我做错了什么?

I had thought the syntax was correct on both of these however every time I make the ajax call I get a 400 response. What is it that I am doing wrong?

推荐答案

您正在向服务器发送完全损坏且无效的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.

这篇关于在jquery ajax帖子上不断收到400(Bad Request)到MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆