Justin L.
Justin L.

Reputation: 1030

How do you pass and receive a nested array of objects using AJAX (jquery) into a c# WebMethod?

I'm trying to pass some data to a WebMethod in a Code Behind .cs file. The data resembles the object below, where there's an array that can have any number of additional objects.

var data = {
    id: "123",
    formula: "liquid",
    chemicals: [
        {
            id: "223",
            amount: "0.2",
            units: "lb/gal",
        }, 
        {
            id: "363",
            amount: "8.8",
            units: "g/li",
        }
    ]
};

The ajax method looks like this:

$.ajax({
    type: "POST",
    url: "index.aspx/SaveData",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

Where I'm struggling is the WebMethod definition to receive the array of objects.

When I simply send over the top level strings id and formula, it works fine. That web method looks predictable:

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

When I try to include the chemicals array, I get a failure response. I'm not sure how to match it. I've tried string, string[], and a few others. Any thoughts on how to properly receive this data in a WebMethod?

Upvotes: 0

Views: 1015

Answers (1)

feeeper
feeeper

Reputation: 3017

You may add Chemicals class (or struct):

public class Chemicals
{
    public string Id { get; set; }
    public string Amount { get; set; }
    public string Units { get; set; }
}

and use it in your webmethod like that:

[WebMethod]
public string SaveData(string id, string formula, List<Chemicals> chemicals)
{ 
  // do cool stuff
}

If you don't want to create one more class you can wrote something like that (with casting to Dictionary<string, object> each array's entry):

[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"]);
  }
}

You can't use List<Dictionary<string, object>> (or any other IEnumerable<IDictionary<string, object>>). See more here.

Upvotes: 1

Related Questions