如何使用 AJAX (jquery) 将嵌套对象数组传递和接收到 c# WebMethod 中?

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 定义。

当我简单地发送顶级字符串 idformula 时,它工作正常。该网络方法看起来可以预测:

[WebMethod]
public static string SaveData(string id, string formula)
{
    // do cool stuff
}

当我尝试包含 chemicals 数组时,我收到失败响应。我不确定如何匹配它。我试过 stringstring[] 和其他几个。关于如何在 WebMethod 中正确接收此数据的任何想法?

您可以添加 Chemicals class(或结构):

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
}

如果你不想再创建一个 class 你可以写类似的东西(转换为 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>>)。查看更多 here.