gpt4 book ai didi

JavaScript 数组到 MVC Controller

转载 作者:行者123 更新时间:2023-11-29 21:14:28 25 4
gpt4 key购买 nike

我有一个简单的 JavaScript 数组,我正试图将其传递给 Controller ​​

function SubmitData()
{
var operationCollection = new Array();

var test1 = { name: "Bill", age: "55", address: "testing" };
operationCollection.push(test1);
var test2 = { name: "Ben", age: "55", address: "testing" };
operationCollection.push(test2);
var test3 = { name: "Flo", age: "55", address: "testing" };
operationCollection.push(test3);


var dataToPost = JSON.stringify(operationCollection);


$.ajax({
type: "POST",
url: "Home/AddPerson",
datatype: JSON,
data: { methodParam: dataToPost },
traditional: true

});
}

C# Controller 有一个类

public class newEntry
{

public string name { get; set; }
public string age { get; set; }
public string address { get; set; }

}

和方法

public void AddPerson(List<newEntry> methodParam)
{

foreach (newEntry item in methodParam)
{
string name = item.age + item.address;

}
}

当我在调试中运行代码时,传递给 Controller ​​方法的值始终为 NULL 或 0。我似乎无法让数组正确传递。我在以前的帖子中读到,traditional: true 将解决此问题……但它不适合我。有人有什么想法吗?

最佳答案

尝试将此添加到您的方法的签名中:

[HttpPost]
public void AddPerson(List<newEntry> methodParam)

同样如 Gavin 所说,使用 data: dataToPost

关于JavaScript 数组到 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40026670/

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