I use the .each()
method for ASP.NET WebMethod
calls that return JSON strings. In this example, it populates a listbox with the values returned from the Ajax call:
async: true,
type: "POST",
url: "Example.aspx/GetValues",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
var list = $('<select />');
$.each(data.d, function(){
var val = this.Value;
var text = this.Text;
list.append($('<option />').val(val).text(text));
});
$('#listbox').empty().append(list.find('option'));
},
ASP.NET has a built-in JSON serializer that automagically converts a class into the JSON string you see at the bottom of this post. Here is an example class that can be returned by the WebMethod
:
public class Tuple
{
public string Text;
public int Value;
public Tuple(string text, int val)
{
Text = text;
Value = val;
}
}
And the WebMethod
itself:
[WebMethod]
public static List<Tuple> GetValues()
{
List<Tuple> options = new List<Tuple>();
options.Add(new Tuple("First option", 1));
options.Add(new Tuple("Second option", 2));
return options;
}
When you specify dataType: "json"
in the jQuery Ajax options, the string is automatically converted into a Javascript object, so you can simply type this.Text
or this.Value
to get the data.
Here is the resulting JSON returned from the WebMethod
above:
{"d":[{"Value":1,"Text":"First option"},{"Value":2,"Text":"Second option"}]}
Note: the data.d
parameter (and likewise the first value seen in the JSON string) is explained here.