Simon Price Simon Price - 2 months ago 7
jQuery Question

Unable to get items from List of Class in JSON response

In .Net I am using an AJAX call that returns me a list of a class, in this list one of the properties is a list of Email \ Contact information.

When I get the JSON data back from the Web Method, I am iterating through it and getting the information out as I need until I come to iterate through the list of Email \ Contact Information.

Using this code

if (data.d[0].Emails.length > 0) {
$.each(data.d[0].Emails, function () {
var something = "";
});
}


the object data.d[0].Emails has a length that is greater than 0, and if I look at this using my debugger I can see all the values that I am expecting.

However, the issue that I am having is when I get into the $.each data.d[0].Emails becomes undefined and all the information that I am after is lost.

When debugging in Visual Studio the message I get is 'data' is underfined

I would be grateful to understand how and where I am going wrong and to be able to get the information out.

this is the entire ajax method

$.ajax({
type: "POST",
url: "Admin.aspx/GetCmcContactInformation",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {

var d = data.d;
console.log(d);
$("#MainContent_txtAddressLine1").val(data.d[0].AddressLine1);
$("#MainContent_txtAddressLine2").val(data.d[0].AddressLine2);
$("#MainContent_txtCity").val(data.d[0].City);
$("#MainContent_txtPostcode").val(data.d[0].PostCode);
$("#MainContent_txtCmcComments").val(data.d[0].Notes);

if (data.d[0].Emails.length > 0) {

if (data.d[0].Emails.length > 0) {
$.each(data.d[0].Emails, function (index, email) {
var something = "";
});
}
}

$("#saveModal").modal("hide");
},
error: function (data) {
console.log("error :" + data);
console.log(data);
$("#saveModal").modal("hide");
$("#newUser").hide("slow");

}
});


thanks

Simon

Answer

It may just be your sample code, but it appears that you are using the wrong method signature for your callback. If you refer to the documentation for $.each, you need to define two arguments for the callback. In the sample code below each item would be available in the email argument:

if (data.d[0].Emails.length > 0) {
   $.each(data.d[0].Emails, function (index, email) {
       var something = "";
   });
}