Thursday, January 15, 2009

Using Json in Asp.net Application

In this post i will try to explain you how you can use Json in your web application , So that you can response to the user request more quickly and avoid unnecessary postbacks. It is very basic article on json used in asp.net, and it is written for the reader who are not familiar with the json or did't know how to the json in asp.net or any of the web language.

What is Json

JSON, according to the official website for JSON, is a lightweight data interchange format that is a text-based, human readable format that is used to represent objects, arrays, and other data types that is mainly used to exchange such data types over the network.

If you look at the JSON site you can see that they have explain the format of data used in the json in great detail but i will explain you the basic data format supported by json. Data format consist of name/value format, where name is the you can use to get the value. And important point is the colon(:) sign between the key and value.

How to use Json

Let us start how can we use json in our web application. For this example of how to use json in web application i have used the "northwind" database and from that database i have used following tables
  1. "region" table which is used as the parent table
  2. "territories" table which is used as child table as it contain the regionid as foreign key in the territories table.
In the default page i have used two dropdownlist controls
  1. ddlRegion dropDownList which is used as parent control and it will be filled with the region from the default page , when the page is first loaded.
  2. ddlTerritory dropDownList which is used as child control and it will be filled when then onchange event is fired in javascript, by using ajax request.
For this example i have used vb.net as code behind language you can change it to your favorite language like C# or what ever you like. This is the some introduction of what i have used in the application so that you better know which controls and database is used in the application. Now let me explain you the core section of the application so that you will get understanding of it.
First of all set start with the ddlRegion dropDownList control which is used as parent control, i have attach the onchange event of the javascript event in the code behind file. Here i have passed the control itself to the ddlRegionChange function so that i can use it in that function.

ddlRegion.Attributes.Add("onchange", "ddlRegionChange(this)")
Now lets come to the ddlRegionChange function. Below is the definition of the ddlRegionChange function.
function ddlRegionChange(currentControl)
{
xmlHttp = getXMLHttpObject();

var intSelectedIndex = currentControl.selectedIndex;
var regionID = currentControl.options[intSelectedIndex].value;

var url="ResponsePage.aspx";
url=url+"?regionID="+ regionID;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
Let us start the coding of ddlRegionChange function . In the first statement i have initialized the xmlHttp which is declared globally. And i have used getXMLHttpObject() function which return the xmlHttp object,is used to check the browser and then initialized the xmlHttp object which is assign to the global xmlHttp object. In the second statement i have declared a variable called intSelectedIndex which is used to store the selected value of the ddlRegion( which is passed as parameter to the ddlRegionChange function. In the next statement i have declared and initialize regionID variable which will store the selected item value.In the next statement i have declared and initialized the url variable, which will call the ResposnePage.aspx and also passed the regionID as parameter and as usual i have passed the random number so that each time fresh requestion is passed to the ResponsePage.aspx.
Here is code of the ResponsePage.aspx , i have paste the function which is used to write json format data.
Private Sub getTerritory()
Dim strQuery As String = String.Concat("Select TerritoryID, TerritoryDescription from territories where RegionID=", intRegionID)
Dim getRegionConnection As SqlConnection = New SqlConnection(strQueryString)
getRegionConnection.Open()
Try
Dim getRegionCommand As SqlCommand = New SqlCommand(strQuery, getRegionConnection)
Dim getRegionReader As SqlDataReader = getRegionCommand.ExecuteReader()

Response.Write("[")
While (getRegionReader.Read())
Response.Write("{" + ControlChars.Quote + "TerritoryID" + ControlChars.Quote + ":" + ControlChars.Quote + getRegionReader.GetString(0).Trim() + ControlChars.Quote + ",")
Response.Write(ControlChars.Quote + "TerritoryDescription" + ControlChars.Quote + ":" + ControlChars.Quote + getRegionReader.GetString(1).Trim() + ControlChars.Quote + "},")
End While
Response.Write("]")

Catch ex As Exception
Finally
getRegionConnection.Close()
End Try
End Sub
In the above function i have stored the passed regionID in the global variable name intRegionID . In the first statement of the function i have construct simple select statement which will fetch territoryID and territoryDescription from territories table based on the regionID. Next i have declared the connection object and passed connection string to the connection object. after the connection obejct i have declared the command object and passed the query and also the open connecton object to the command object constructor. In the next statement i have declared the sqlDataReader object and call the ExecuteReader function of the command object to fetch the territoryID and the territoryDescription.
In the function i have used the while loop to construct the following format of the json data.
[
(Key) : (Value) , (Key) : (Value) (comma)
{"TerritoryID": "TerritoryID","TerritoryDescription": "Territory Description"},
{"TerritoryID": "TerritoryID","TerritoryDescription": "Territory Description"}
]
Here i have used TerritoryID as key and the value of that key value will be the TerritoryID fetched from the database and after comma i have TerritoryDescription key and the value of TerritoryDescription key will be the territory description fetch from the database. as i need territoryID and territory description as one set so i have enclosed them in right opening curly braces and end with right closing curly braces. after on obejct is constructed i have put comma(,) after that and the start with same steps as in the first to construct the second one and so on.

Here is code to the consume the json data which is return from the ResponsePage.aspx.
function stateChanged()
{
if (xmlHttp.readyState==4)
{
var ddlTerritory = document.getElementById("<%=ddlTerritory.ClientID%>");
var jsonObject = xmlHttp.responseText.parseJSON();
ddlTerritory.innerHTML ='';
for(var intCounter=0; intCounter< style="color: rgb(51, 51, 255);">var newOption = document.createElement("Option")
newOption.value = jsonObject[intCounter].TerritoryID ;
newOption.text= jsonObject[intCounter].TerritoryDescription;
ddlTerritory.options.add(newOption);
}
}
}

In the ddlRegionChange function i have assign the onreadystatechange of the xmlHttp object a function which will be executed when the state of the xmlHttp readyState is changed. Below is the statement to assign the function to the onreadystatechange of the xmlHttp object

xmlHttp.onreadystatechange=stateChanged;

when the function is called what we did is check reaystate of the xmlHttp object, here are the possible value of the readystate of the xmlHttp object.
readystate Value
Description
0
open has not yet been called
1
send has not yet been called but open has been called
2send has been called but no response from server
3
data is in the process of being received from the server
4
response from server has arrived
But we re interested in the readystate value 4 which indicate that our ajax request is successfully. Assuming the response from the server is formatted in a JSON string object, the code first grasps the response text by using the xmlHttp property called responseText. Once the text is available, the code parses the response text using the parseJSON() function. This function will convert any well-formatted JSON string object into a JSON object.Once we have a valid JSON object, we access the object properties the same way we access any C# or VB.NET object, by simply specifying the object name, a “.” and the name of the property. To fill the ddlTerritory dropDownList control i have used the TerritoryID and TerritoryDescription key value to get there values. You can download the json.js file from the here which is utility class prepared by the JSON team for the use of json .You can download the source code from here
All and any comments / bugs / suggestions are welcomed!


1 comment:

Anonymous said...

A fastidious post indeed!
I was waiting for a JSON post for a long time :)