Search code examples
javascriptc#asp.netjsonwebmethod

Returning MULTIPLE Lists using JSON and Serializer


I'm sending a List from my ASP.NET WebMethod to my Javascript using this:

List<Person> plist = new List<Person>();

string json = "";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = oSerializer.Serialize(plist );

return json;

And I'm using this to retrieve these values from my JS:

function onSuccess(val) {
        var obj = JSON.parse(val)
        obj.forEach(function (entry) {
               console.log(entry);
       });
}

Everything works well. However now I want to return MULTIPLE lists such as:

List<Person> plist = new List<Person>();
List<Car> carlist = new List<Car>();
List<Car> jeeplist = new List<Car>();

using the same mechanism I used before. How can I insert two lists to the Serializer and print them from my JS?

EDIT

How do I get the values from the JS? Is this the way?

obj.forEach(function (entry) {
         entry.forEach(function (act)
         {
               console.log(act);
         })
});

Solution

  • struct TwoLists
    {
        public List<Person> plist;
        public List<Car> carlist;
    }
    

    ...

    TwoLists lists;
    lists.plist = new List<Person>();
    lists.carlist = new List<Car>();
    ...
    string json = "";
    System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    json = oSerializer.Serialize(lists);
    
    return json;
    

    ...

    function onSuccess(val) {
        var obj = JSON.parse(val);
        obj.plist.forEach(function (entry) {
            console.log(entry);
        });
        obj.carlist.forEach(function (entry) {
            console.log(entry);
        });
    }