gpt4 book ai didi

jquery - JSON 数据未在 AJAX POST 请求中发送

转载 作者:行者123 更新时间:2023-12-01 08:41:44 24 4
gpt4 key购买 nike

我有一个 AJAX 请求,它使用 POST 请求将 JSON 对象从 MVC View 发送到 Controller :

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);
}
});
}

Controller 操作具有以下定义:

[HttpPost]
public ActionResult SubscribeSecurities(string subscriptions)
{

JSON 具有以下格式:

{
"Subscriptions": {
"Obj1": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj2": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj3": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
}
}
}

什么可能导致问题?

编辑

以下是我在创建对象来存储 JSON POST 请求返回的值后所做的更新。

JSON

var test = {

"Obj1": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj2": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj3": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
}

}

捕获 JSON 的模型

   public class RootObject {
// Give this a better name. RootObject is a horrible name.

public IEnumerable<SubscriptionObj> Subscriptions { get; set; }
}

public class SubscriptionObj
{
public Int64 Value1 {get;set;}
public Int64 Value2 {get;set;}
public Int64 Value3 {get;set;}
public Boolean Value4 {get;set;}
}

最佳答案

您的 Controller 需要一个字符串,但您正在向它发送一个自定义对象。

将您的 json 更改为字符串,或者将 Controller 期望的内容更改为与正在发送的内容匹配的对象...例如:

public class RootObject {
// Give this a better name. RootObject is a horrible name.

public Subscriptions Subscriptions {get;set;} = new Subscriptions();
}


public class Subscriptions {
public Subscription Obj1 {get;set;} = new Subscription();
public Subscription Obj2 {get;set;} = new Subscription();
public Subscription Obj3 {get;set;} = new Subscription();
}


public class Subscription {
public Int64 Value1 {get;set;}=0;
public Int64 Value2 {get;set;}=0;
public Int64 Value3 {get;set;}=0;
public Boolean Value4 {get;set;}=false;
}

您的 MVC Controller 会自动将传入的 json 字符串反序列化为真实对象。如果反序列化的对象不是字符串,它不会将传入的 json 传递给 Action 的字符串参数。

关于jquery - JSON 数据未在 AJAX POST 请求中发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46308119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com