Your backend code should look something more like this (WebService.cs in my example, which is the CodeBehind for WebService.asmx ):
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public class JsonResult
{
public string key, label, open;
public List<Children> children;
}
public class Children
{
public string key, label;
}
[WebMethod]
public List<JsonResult> test()
{
List<Children> child = new List<Children>();
child.Add(new Children
{
key = "211",
label = "Burger"
});
List<JsonResult> result = new List<JsonResult>();
result.Add(new JsonResult
{
key = "1",
label = "Food",
open = "false",
children = child
});
return result;
}
}
This code sends the created list as JSON - which looks like this when jQuery receives it:
{"d":[
{
"__type":"WebService+JsonResult",
"key":"1",
"label":"Food",
"open":"false",
"children":[
{
"key":"211",
"label":"Burger"
}
]
}
]}
Then, the jQuery AJAX is very simple, like so:
$.ajax({
type: "POST",
url: "/WebService.asmx/test",
contentType: "application/json",
success: function (response) {
var jsonResponse = response.d;
}
});
Now you can access each element as native JavaScript objects, like I show here in the success callback when assigning each object to a variable. Now you can do anything you want to with the data.
success: function (response) {
var jsonResponse = response.d;
for (var i = 0; i < jsonResponse.length; i++) {
var key = jsonResponse[i].key;
var label = jsonResponse[i].label;
var open = jsonResponse[i].open;
var children = jsonResponse[i].children;
for (var a = 0; a < children.length; a++) {
var key = children[a].key;
var label = children[a].label;
}
}
}
This is 100% tested and working. Let me know if there's anything else I can help you with.
$("#test").html(msg);contentTypeon your$.ajaxcall, you're responsible for serializing the data you're sending from the client to the server in that form (e.g., you can't dodata: {}). jQuery only does serialization for you with the standard URI-encoded form. Unless you're sending JSON to the server, removecontentType: "application/json".