In this last section of this article, I am going to provide
a sample demo. We will go through the code step-by-step and show you all the
needed information to enable you to develop such AJAX/JSON enabled ASP.NET web
applications.
Figure 1: JSON Demo Web Application

To start with, let me explain the main idea of the
application. As you can see from the form above, it asks the users to select an
employee name from the DropDownList. Once an employee is selected using
AJAX/JSON, the details of the selected employee will be shown below the
DropDownList.
Listing 10 show the code of the above ASP.NET web form.
Listing 10
<div id="page">
<div id="header">
<h1>Populating Data with JSON</h1>
</div>
<div id="content">
Select an employee to check his/her record:<br />
<asp:DropDownList ID="ddlEmployees" runat="server" onchange="GetEmployeeDetails()">
<asp:ListItem Value="-1" Text="Select Employee"></asp:ListItem>
<asp:ListItem Value="1" Text="Bilal"></asp:ListItem>
<asp:ListItem Value="2" Text="Wessam"></asp:ListItem>
<asp:ListItem Value="3" Text="Sami"></asp:ListItem>
<asp:ListItem Value="4" Text="Haissam"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<div id="statusDisplay">
<div id="innerStatusDisplay"></div>
</div>
<br /><br />
<div id="employeeDetails" style="visibility:hidden">
<table>
<tr style="font-weight: bold">
<td>First Name</td><td>Last Name</td><td>Years of Experience</td>
</tr>
<tr>
<td class="datacell"><span id="empFname"></span></td>
<td class="datacell"><span id="empLname"></span></td>
<td class="datacell"><span id="empExperience"></span></td>
</tr>
</table>
</div>
</div>
</div>
An onchange function has been added to the DropDownList so
that, when the user selects an item from the DropDownList, a JavaScript
function will be fired! The JavaScript method to fire named GetEmployeeDetails
will start an AJAX request to the server by requesting an ASP.NET web form and
supplying the employee ID to whom the details should be displayed.
Listing 11: GetEmployeeDetails function
function GetEmployeeDetails() {
postRequest = new HttpRequest();
postRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
postRequest.failureCallback = requestFailed;
setStatusText("");
ResetEmployeeDetails();
// Get Employee Selected
var n = document.forms[0].elements["ddlEmployees"].selectedIndex;
var empID = document.forms[0].elements["ddlEmployees"].options[n].value;
// Validate the employee ID
if (empID == -1) {
setStatusText("Please select a valid employee.");
return;
}
var empID = encodeURI(empID);
postRequest.url = "GetEmployeeDetails.aspx";
postRequest.successCallback = responseOK;
postRequest.post("EmpID=" + empID);
}
The function starts by creating a new instance of the
XmlHttpRequest object using a wrapper class called HttpRequest. Then it defines
the content type of the request and the failure callback method in case a
problem happened while sending the request or receiving a response from the
server.
The HttpRequest is a wrapper class created by Mike Hall.
Mike has a very educative article on AJAX and I recommend every one of you to
check it out and learn from it. It is an AJAX reference if you are planning to
introduce AJAX to your web applications. The article can be found here. In last page of this
article Mike presents the HttpRequest object which is nothing but a wrapper
over the XMLHttpRequest object in either IE7 and FireFox or the different
Microsoft ActiveX XmlHttpRequest objects.
The code then gets the employee that was selected from the
DropDownList. The employee ID is then encoded and this step is done intentionally
because the function is using POST to request another ASP.NET web form to
process the request.
Finally, the URL to be requested is assigned to the URL
property of the instance of the HttpRequest object and a success callback
method is specified, which is the method to fire when the AAJX request is
completed and that the response is OK. The last line of the method posts the
asynchronous request to the server, requesting the GetEmployeeDetails ASP.NET
web form.
Listing 12: GetEmployeeDetails Server side code
protected void Page_Load(object sender, EventArgs e)
{
// Validate the Form object
if (Request.Form["EmpID"] != null)
{
if (!string.IsNullOrEmpty(Request.Form["EmpID"].ToString()))
{
// Request is OK
this.requestOK = true;
// Get the value of the EmployeeID
Employee employee = null;
int empID = Convert.ToInt32(Request.Form["EmpID"].ToString());
// Prepare object
switch (empID)
{
case 1:
// Employee Bilal was selected
employee = new Employee("Bilal", "Haidar", 1, new string[]
{
"2005", "2006"
}
);
break;
case 2:
// Employee Wessam was selected
employee = new Employee("Wessam", "Zeidan", 2, new string[]
{
"2004", "2005", "2006"
}
);
break;
case 3:
// Employee Sami was selected
employee = new Employee("Sami", "Souki", 3, new string[]
{
"2003", "2004"
}
);
break;
case 4:
// Employee Haissam was selected
employee = new Employee("Haissam", "Abdul Malak", 4, new string[]
{
"2005", "2006"
}
);
break;
default:
// Wrong Employee Selected
this.requestOK = false;
break;
}
Response.Clear();
Response.ContentType = "application/json";
if (this.requestOK)
{
// Prepare JSON response
string output = Newtonsoft.Json.JavaScriptConvert.SerializeObject
(employee);
Response.Write(output);
}
Response.End();
}
}
}
The page load of GetEmployeeDetails page first retrieves the
employee ID that was posted to it through the AJAX request. This is just a
dummy code that will use a C# switch statement to check the employee ID and
accordingly a new Employee object is constructed.
Once the employee object is created, the code clears the
current response and sets the content type of the response to application/json,
which is the right content type when you are sending JSON data to the client.
After that, the employee object is serialized into a JSON
string object. Finally, the JSON string object is written back to the client.
Assuming the request/response is done safely (most of the
times), the requestOK function will fire on the client. This is the method that
was set to the success callback method of the HttpRequest instance.
Listing 13: Success callback function
function responseOK(httpRequest)
{
// Assume no match was found.
var statusText = "Employee not found!"
// Fill in the FirstName, LastName, and years of experience, if available.
try
{
// Show the employee etails
var empDetails = document.getElementById("employeeDetails");
if (empDetails != null)
empDetails.style.visibility = "";
var jsonObj = postRequest.responseText.parseJSON();
// Set the FirstName
var fname = document.getElementById("empFname");
if (fname != null)
fname.innerHTML = jsonObj.FName.toJSONString();
// Set the LastName
var lname = document.getElementById("empLname");
if (lname != null)
lname.innerHTML = jsonObj.LName.toJSONString();
var exp = document.getElementById("empEmployment");
var splitExp = "";
for (i = 0; i < jsonObj.YearsOfEmployment.length; i++)
{
splitExp = splitExp + jsonObj.YearsOfEmployment[i].toJSONString();
if (i != (jsonObj.YearsOfEmployment.length - 1))
splitExp = splitExp + ",";
}
if (exp != null)
exp.innerHTML = splitExp;
// Update status
statusText = "Employee Details Found";
}
catch (ex){}
setStatusText(statusText);
}
The above function receives the response from the server; it
parses the JSON string object into a JSON object using the JSON utility file
methods. On thing to mention, you should always check if the response text is
null or not before doing any parsing!
Finally, the web form is populated with the details of the
employee who was selected from the DropDownList.
There are still some functions left that I did not mention
in this article that are part of the demo application. Go over them and if you
have any question do not hesitate to contact me and ask me about them.
The following is a snapshot of the page displaying the
details of an employee that was selected from the DropDownList:
Figure 2: Demo in action
