Invalid json returned from aspx page in response to a Client side Ajax call

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi Experts,
I have come across an issue in which I am unable to serialize the Object To Json from the aspx page in reponse to a Client Side Ajax Call..
The code is like this:-
<span style="text-decoration:underline Default.aspx Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JsonandcontrolDemo._Default" %><br/>
<br/>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd <br/>
<br/>
<html xmlns="http://www.w3.org/1999/xhtml <br/>
<head runat="server <br/>
<title>Json Demo</title><br/>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js </script><br/>
<script type="text/javascript" language="javascript <br/>
function GetCust() {<br/>
$.ajax( <br/>
{ <br/>
type: "GET", <br/>
//contentType: "application/json; charset=utf-8", <br/>
data: { id: 5 }, <br/>
url: "CustomerJson.aspx", <br/>
dataType: "json", <br/>
success: function (data) { <br/>
alert("FirstName:" + data.d[0].FirstName + " LastName:" + data.d[0].LastName); <br/>
}, <br/>
error: function (xhr, status, error) { <br/>
alert(Error Occured:+error); <br/>
} <br/>
<br/>
}); <br/>
}<br/>
</script><br/>
</head><br/>
<body onload="GetCust() <br/>
<form id="form1" runat="server <br/>
<br/>
<br/>
<br/>
</form><br/>
</body><br/>
</html>

<span style="text-decoration:underline CustomerJson.aspx(Code-behind)
public partial class CustomerJson : System.Web.UI.Page<br/>
{<br/>
protected void Page_Load(object sender, EventArgs e)<br/>
{<br/>
<br/>
Response.ContentType = "application/json";<br/>
var cust = new Customer<br/>
{<br/>
ID = (Request["id"] == null ? 0 : int.Parse(Request["id"])),<br/>
FirstName = "Nilanjan",<br/>
LastName = "Dutta"<br/>
};<br/>

/ // System.Web.Script.Serialization.JavaScriptSerializer oSerializer =<br/>
//new System.Web.Script.Serialization.JavaScriptSerializer();<br/>
// string sJSON = oSerializer.Serialize(cust);<br/>
// byte[] array = Encoding.ASCII.GetBytes(sJSON);<br/>
// Response.OutputStream.Write(array, 0, array.Length);<br/>
<br/>
var ser = new DataContractJsonSerializer(typeof(Customer));<br/>
ser.WriteObject(Response.OutputStream, cust);<br/>
<br/>
}<br/>
}
<span style="text-decoration:underline Customer.cs
namespace JsonandcontrolDemo.DTO
{<br/>
<br/>
public class Customer<br/>
{<br/>
public int ID { get; set; }<br/>
public string FirstName { get; set; }<br/>
public string LastName { get; set; }<br/>
<br/>
}<br/>
}
Although Id=5 is properly accessed in the code I am unable to get the Json Back..I am constantly getting this error in the error Callback:
ErrorOccured:Invalid JSON:
{"FirstName":"Nilanjan","ID":"5","LastName":"Dutta"}.
Please help. Thanks in advance

View the full article
 
Back
Top