I’m fetching JSON from my ASP .NET website using the following jQuery:
$.ajax({
type: 'POST',
url: '/blah/default.aspx/GetTestData',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(output) {
var viewModel = $.parseJSON(output.d);
ko.applyBindings(viewModel);
}
});
And then using the Knockout library to update my UI. The server-side code in default.aspx to get the data is as follows.
[WebMethod]
public static string GetTestData()
{
var viewModel = null; // Get viewModel data from elsewhere.
return new JavaScriptSerializer().Serialize(viewModel);
}
This works fine in IE but when I try in Chrome and Firefox the JSON does not get returned. My breakpoint server-side does get hit so the web method is being called, but something is happening when it comes back to the browser.
I think it might be related to setting content or MIME types at either the browser or webserver end but I’ve not had any luck yet, does anyone have any suggestions?
You can actually avoid the serialization and parsing by having your Page Method just return your object.
So, it would look like:
On the JavaScript side, it would look like:
So, you don’t need to serialize it in .NET and you don’t need to parse it on the client-side. It is all handled by the “plumbing” on both sides. Also, passing
data: "{}"is important (or if you need parameters, they would go here).Also, if you were calling a web service instead of Page Method, then you need to decorate the class with a
[ScriptService]attribute.