【问题标题】:How do you pass and receive a nested array of objects using AJAX (jquery) into a c# WebMethod?如何使用 AJAX (jquery) 将嵌套的对象数组传递和接收到 c# WebMethod 中?
【发布时间】:2017-01-16 22:15:48
【问题描述】:

我正在尝试将一些数据传递给 .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 中正确接收这些数据的任何想法?

【问题讨论】:

    标签: c# jquery ajax webforms webmethod


    【解决方案1】:

    您可以添加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&lt;string, object&gt; 每个数组的条目):

    [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&lt;Dictionary&lt;string, object&gt;&gt;(或任何其他IEnumerable&lt;IDictionary&lt;string, object&gt;&gt;)。查看更多here

    【讨论】:

    • 你认为有可能做类似的事情,但只使用字典,这样我就可以避免创建一个新类吗?如果是这样,你认为你会怎么做?
    • @JustinL。不幸的是,不,这样做是不可能的。您可以使用object[] chemicals 并将其条目转换为Dictionary&lt;string, object&gt; 等等,但我认为这不是一个好方法。
    • @JustinL。我回答了这个问题吗?
    • 你做到了,我一直在等待后端工程师的回复,说他正在正确接收信息......但我很确定这很好用 - 谢谢!编辑也很有帮助
    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2013-01-30
    • 2017-03-02
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多