Introduction
AJAX, or Asynchronous JavaScript and XML, is a free framework for quickly creating a new generation of more efficient, more interactive, and highly-personalized web experiences that work across all the most popular browsers. AJAX is a relatively new phenomenon, based on technologies that aren't quite new, for creating a way for businesses to interact with customers over the internet.
In this article, we use the current AJAX technique (in its simplest way) to implement an on-demand tree view. Since XML is a common standard and easy to implement, I am using XML in my sample application instead of a database. I have found another article here to build a tree view using AJAX.
History (Skip this section if you are feeling bored)
This technology was introduced first by Microsoft (from my best knowledge) back in 1999, and had been known as "DHTML / JavaScript web application with remote calls". The whole idea of the technology was to allow an internet browser to make an asynchronous HTTP call to remote pages/services and update a current web page with the received results without refreshing the whole page. In the creator's opinion, this should have improved the customer experience, making HTTP pages look and feel very similar to Windows applications.
Because the core implementation of this technology was based on internet browser functionality, the usability was very limited at that time. Several years later, the technology was reborn with new browser support and massive implementation by such giants as Google, Amazon.com, eBay, etc.
Today, it's known as AJAX, and considered as a natural part of any dynamic web page with advanced user experience. Many readymade frameworks are also available on the internet like Microsoft AJAX/ATLAS and Enterprise AJAX.
Why AJAX
This sample application provides a tree view implementation from an XML file. In real scenarios, I have noticed the processing of building the complete tree structure (with many level children) and rendering into the browser takes quite a long time. I attempted different approaches, one of them was building the tree on demand. But I don't like the post back (I am sure you too). Then I found AJAX was the best bet. By this, we could avoid a post back and flickering of the browser; we're just changing the portion of the page, hence reducing the traffic in the server and enhance the performance.
Working
The idea is to build a tree structure using UL and LI tags and use a style sheet and some JavaScript, all together giving some real effects. On page load or a pre-render event, the root node will be loaded; from that, on click of the plus/minus images, you can expand or collapse the tree. You can notice that the child node is generated on the fly (of course, you can cache the data source). Since AJAX is asynchronous, I am displaying an image to indicate that a request is already made to the server.
Implementation
The code files include:
- TreeSource.XML: The source file where the tree structure is defined.
="1.0"="utf-8"
<Nodes>
<Node NodeID="0" NodeName="World" ParentID="-1"></Node>
<Node NodeID="1" NodeName="North America" ParentID="0"></Node>
<Node NodeID="13" NodeName="United States" ParentID="1"></Node>
AJAXroutine.js: The JavaScript file contains all the required methods to handle the asynchronous calls and the standard AJAX methods. JavaScript is the core component in this technology, as you can see. It handles the change detection, data request receipt, and placing of the data on the page.
function Toggle(node){
if (node.nextSibling.style) {
if (node.childNodes.length > 0) {
if (node.childNodes.item(0).nodeName == "IMG"){
...
The core function for the asynchronous request is:
function GetXmlHttpObject(){
var objXMLHttp=null
if (window.XMLHttpRequest){
...
The HTML will look like the following tags:
<ul id="treeUL" class="treeUL">
<li id='10'>
<span title='World' valign='bottom'
onclick="javascript:if (Toggle(this))showContentsEx('divTree0','0','');">
The client SPAN
will call the following function to invoke the server request:
function showContentsEx(div, str, lmsg){ ...
- WebForm1.aspx: The sample .aspx file. It has the root level hard-coded in this sample. I have put some styles to make it look nice. You can build that section on the fly.
- WebForm1.aspx.cs: The code behind of the .aspx file.
- GetTreeContents.aspx: Empty in the design mode.
- GetTreeContents.aspx.cs: All the client requests process this code-behind and renders in the browser. When the client HTTP request is made, the following scripts will execute on the server and render the HTML on the browser.
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
string key = Request.QueryString["q"];
if (key != null)
{
String path = Server.MapPath(ConfigurationSettings.AppSettings["XmlTree"]);
XmlDocument xmlTree = new XmlDocument();
xmlTree.Load(path);
System.IO.StringReader xmlSR = new System.IO.StringReader(xmlTree.OuterXml);
DataSet ds = new DataSet();
ds.ReadXml(xmlSR);
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = " ParentID = '" + key + "'";
Response.Write ("<ul class='wTreeStyle'>");
for(int i=0; i < dv.Count; i++)
{
Response.Write (string.Format("<li id='{0}'><span valign='bottom' " +
"title='{1}' onclick=\"javascript:if (Toggle(this))" +
"showContentsEx('divTree{0}','{0}','');\"><IMG " +
"align='bottom' SRC='plus.gif'> <span class='treeStyleNode' >" +
"{1}</span></span><span id ='divTree{0}'></span></li>",
dv[i]["NodeID"].ToString(), dv[i]["NodeName"].ToString()));
}
Response.Write ("</ul>");
} ...
- Images: Loading.gif, plus.gif, minus.gif
- Web.config: for the key
<add key="XmlTree" value="~/TreeSource.XML" />
For simplicity, I am putting only the required code since I want to share the implementation; you can customize this or enhance it in your projects.
Conclusion
This article is aimed at illustrating the simplicity of using AJAX technology in any ASP.NET application. It is up to developers who want to use the technology in this way. I just did a practical implementation of the technology since the core code is already in place. I have tested the application in MS Visual Studio V.7/ MDE 2003 and MS .NET Framework 1.1. And C# - ASP.NET.
Credits
With the help of God, I am submitting this article here. I would like to thank the Codeproject.com community and some other information web sites for providing a great service. I also thank my colleagues and friends for their support, cooperation, and reviewing this article.
You can download the files, and I hope it is a completely working one. Most readers (I am one of them) want a good sample to start with. I tried my best for the cause. I hope you will enjoy this simple implementation.