当前位置:  开发笔记 > 后端 > 正文

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

如何解决《在jqueryajax帖子上不断收到400(BadRequest)到MVC控制器》经验,为你挑选了1个好方法。

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



1> Darin Dimitr..:

您正在向服务器发送完全损坏且无效的JSON字符串.控制器动作拒绝它是正常的.除此之外,您还要在注释中添加contentType指定要发送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变量做了什么,但我觉得这是错误的.

推荐阅读
郑谊099_448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有