发送POST请求时无效的JSON原语

我有以下ajax请求,我正在尝试将JSON对象发送到服务器:

function sendData(subscriptionJson) { $.ajax({ type: "POST", url: '@Url.Action("SubscribeSecurities", "Subscription")', data: "{'subscriptions': subscriptionJson}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { console.log("success response: " + response.responseText); alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime); }, failure: function (response) { console.log("failure response: " + response.responseText); alert(response.responseText); }, error: function (response) { console.log("error response: " + response.responseText); alert(response.responseText); } }); } 

基于这篇文章中的最佳答案,我在“data”属性周围添加了引号,但是我收到一条错误,说“subscriptionJSON”未被识别。 我尝试使用示例字符串进行测试,如下所示:data: "{'foo':'foovalue', 'bar':'barvalue'}",但是当控制器获取subscriptionJson对象的参数时,它为null 。

通过POST请求将JSON对象发送到ASP .NET MVC控制器的官方方法是什么?

您的问题是因为您没有发送有效的JSON。 您需要用双引号括起键。 另外, subscriptionJson是代码中的文字字符串。 你需要它是一个字符串变量。

 data: '{"subscriptions": ' + subscriptionJson + '}', 

或者,更好的是,只需为jQuery提供一个普通对象,让它为您编码值:

 data: { subscriptions: subscriptionJson }, 

在Ajax语句之前创建一个简单的java脚本对象。 使用数据构建ajax选项

 data : { parameterName : jsobject } 

注:(无报价)

确保控制器操作方法具有相同的parameterName。