Trying to learn some jquery / js and some ajax here. I created a simple asp.net web form project with the following:
namespace JSONTest
{
public partial class _Default : System.Web.UI.Page
{
public class Contact
{
public string Name { get; set; }
}
List<Contact> contacts = new List<Contact>
{
new Contact{ Name = "George" },
new Contact{ Name = "Mike" },
new Contact{ Name = "Steve"}
};
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Contact> GetContacts()
{
return contacts;
}
}
}
My js file was simply this:
$(document).ready(function () {
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetContacts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (key, val) {
console.log(val.Name);
});
}
});
});
I would of expected the javascript console to display the contact’s name but it just says Failed to load resource: The server responded with a status of 500 (internal server error) http://localhost:someNumber/Default.aspx/GetContacts. I’m not sure what I am doing incorrectly?
My syntax was a little off. Notice the added
staticto the web method.The server returns the JSON wrapped – so you need to use
data.d.Another way to do this is use an ASMX service instead of just a method on a page. This makes it so the methods don’t have to be static and it’s an actual web service.
And the javascript: