[英]How do you pass and receive a nested array of objects using AJAX (jquery) into a c# WebMethod?
我正在尝试将一些数据传递到.cs
文件背后的代码中的WebMethod。 数据类似于下面的对象,这里有一个可以包含任意数量其他对象的数组。
var data = {
id: "123",
formula: "liquid",
chemicals: [
{
id: "223",
amount: "0.2",
units: "lb/gal",
},
{
id: "363",
amount: "8.8",
units: "g/li",
}
]
};
ajax方法如下所示:
$.ajax({
type: "POST",
url: "index.aspx/SaveData",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
我在努力的地方是WebMethod定义,以接收对象数组。
当我简单地发送顶级字符串id
和formula
,它可以正常工作。 该网络方法看起来可以预测:
[WebMethod]
public static string SaveData(string id, string formula)
{
// do cool stuff
}
当我尝试包含chemicals
阵列时,我会收到故障响应。 我不确定如何搭配。 我已经尝试过string
, string[]
和其他一些。 关于如何在WebMethod中正确接收此数据的任何想法?
您可以添加Chemicals
品类(或结构):
public class Chemicals
{
public string Id { get; set; }
public string Amount { get; set; }
public string Units { get; set; }
}
并像这样在您的网络方法中使用它:
[WebMethod]
public string SaveData(string id, string formula, List<Chemicals> chemicals)
{
// do cool stuff
}
如果您不想再创建一个类,则可以编写类似的内容(将每个数组的条目转换为Dictionary<string, object>
):
[WebMethod]
public void SaveData(string id, string formula, object[] chemicals)
{
for (int i = 0; i < chemicals.Length; i++)
{
// i-th entry in the chemicals array.
var entry = ((Dictionary<string, object>)chemicals[i]);
Debug.WriteLine(entry["id"]);
}
}
您不能使用List<Dictionary<string, object>>
(或任何其他IEnumerable<IDictionary<string, object>>
)。 在这里查看更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.