您正在向服务器发送一个完全损坏且无效的 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 https://github.com/douglascrockford/JSON-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
变量,但我觉得这是错误的。