Tuesday, May 17, 2011

ASP.NET and Json

JSON (Javascript Object Notation) is a language independent open standard for representing data. It is human readable and light weight compared to XML. JSON can be used to serialize objects and transmit data.

So - how do you convert .net objects to JSON and pass to javascript function. I could not find a good/simple example on this, which lead me to write the below example.

As always – lets go directly to example and see JSON and .net at work .

1) Create an ASP.Net application. Create a class which we will pass to javascript (client side) as JSON
public class ChartEx
public string name { get; set; }
public List<int> data{ get; set; }

2) In the page load of default.aspx ,create an instance of the object and fill data
ChartEx oEx = new ChartEx();
oEx.data = new List();

oEx.name = "Revenue";

3) Create a public property for the page.

public string Series1 { get; set; }

4) Serialize the object using Javascript serializer (in namespace Sytem.Web.Script.Serialization) And set serialized data to the public property.

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string strData = oSerializer.Serialize(oEx);
Series1 = strData;

5) Access the public property from ASPX page JS function inside script block
function ShowAlert()
var sdata =<%=Series1 %> ;

6) And call the js function in Load event of the page as given below.
<body onload="ShowAlert();">

Run the application and we can see that the .net object is serialized to a JSON object which can be now be used by a JS function. Isn’t that awesome (and easy)?

No comments: