I’ve been tasked with converting a one-page ASP.NET MVC 3 web app to ASP.NET 3.5 Web Forms app due to some incompability with Sharepoint. I’m unable to the access the property of an object in json result of the web forms app. Can anyone tell me what I’m doing wrong? Also, is it better to use a WCF service or a regular web service when using web forms for returning json data? Can anyone give me some examples? Is it better to use in-built Javascript serializer or JSON.net library? Here’s my code –
MVC method –
public ActionResult LoadPerson()
{
var p = new Person;
p.Name = "Bob";
return Json(new { value = p}, JsonRequestBehavior.AllowGet); //what is the equivalent of this in webforms so I can access the properties directly?
}
MVC javascript file –
var person;
$.ajax({
url: 'Home/LoadPerson',
type: 'GET',
async: false,
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
person = result.value;
}
});
alert(person.Name); //works fine.
Web Forms code-behind –
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string LoadPerson()
{
var p = new Person();
p.Name = "Bob";
var serializer = new JavaScriptSerializer();
return serializer.Serialize(p);
}
Web Forms javascript –
var person;
$.ajax({
url: 'Default.aspx/LoadPerson',
type: 'POST',
async: false,
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
person = result.d;
}
});
alert(person.Name); //undefined. Why?
Your problem is due to manually JSON serializing the response from your page method. After running
JSON.parse()on the response from your service, jQuery is left with a JSON string instead of an object with properties like.Name.ASP.NET automatically handles that step (using JavaScriptSerializer internally itself, no less). If you just return the object and let ASP.NET handle the translation, it should work as you expect:
See this post for a more detailed explanation: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
While you’re changing the code, I recommend avoiding the
async: falseapproach. Since JavaScript runs in single, shared thread, and shares that thread with UI rendering in most browsers, any synchronous code introduces a whole host of performance issues. That may even lead to your script presenting an unresponsive script dialog, giving your users the option to cancel its execution.