0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Do you think it's possible to do something similar but just use a dictionary so I can avoid creating a new class? If so, how do you think you'd do it?
@JustinL. Unfortunately, no, it's impossibe to do so. You can use object[] chemicals and cast its entries to the Dictionary<string, object> and so on but I think that it's not a good approach.
@JustinL. Did I answer to the question?
You did, I've been waiting to hear back from a backend engineer that he's receiving the info properly... But I'm pretty sure this works well -- thanks! The edit was helpful too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.