Javascript MVC jQuery Ajax Post-只能使其使用硬编码的值
所以我有一个基本的管理员在接受一个帖子Javascript MVC jQuery Ajax Post-只能使其使用硬编码的值,javascript,jquery,ajax,asp.net-mvc-4,Javascript,Jquery,Ajax,Asp.net Mvc 4,所以我有一个基本的管理员在接受一个帖子 [HttpPost] public ActionResult Submit(string postCost) { //Do stuff here before sending back redirect details... return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") }); } 我
[HttpPost]
public ActionResult Submit(string postCost)
{
//Do stuff here before sending back redirect details...
return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") });
}
我通过jquery ajax方法发布:
$.ajax({
url: partyURL,
dataType: 'json',
contentType: 'application/json', //charset=utf-8',
type: 'POST',
data: { postCost: postageCost}, //**This fails!**
//data: "{'postCost':'3.50'}", //**This works**
success: function (response) {
if (response.result == 'SoldOut') {
$("#soldOut").show();
}
else if (response.result == 'Redirect') {
//All good, onward to confirmation page
window.location = response.url;
}
},
error: function (xhr, status, error) {
// Error handling here
}
});
其中postageCost变量在返回状态500失败时发送:
postageCost = '3.50';
postageCost = JSON.stringify(postageCost); //also fails with this
但是如果我硬编码数据定义为
data: "{'postCost':'3.50'}",
它很好用
因此,关键必须在于我如何处理数据元素?您需要这样做
var datum = {'postCost': '3.50'};
data: JSON.stringify(datum), //Ajax call data
检查“网络”选项卡以查找返回的错误。(你有没有试过
data:JSON.stringify({postCost:postageCost}),
@StephenMuecke-data:JSON.stringify({postCost:postageCost})有效。如果你作为答案发布,你可以得到糖果。谢谢:)厄齐尔刚刚发布了一个答案,所以你可以接受(尽管你不需要postCost
周围的引号)。另外,为什么您的methods参数不是(decimal postCost)
?您的控制器需要的是字符串,而不是json或对象Submit(string postCost)
你不能改变这一点,这样你就可以一直使用json了吗?好的@StephenMuecke-我本来说过,在ozils回答之前,我尝试你的答案时,你可以得到分数,但他可以得到。为什么要接受字符串?我想我已经在房子里逛了这么久了,我已经把它修好了。更改谢谢:)谢谢厄齐尔:)我还没意识到你可以在数据段中进行字符串化。