玄铁剑

成功的途径:抄,创造,研究,发明...
posts - 128, comments - 42, trackbacks - 0, articles - 174

Building Tree View on demand using AJAX

Posted on 2007-06-12 21:38 玄铁剑 阅读(520) 评论(0)  编辑 收藏 引用 所属分类: ASP.NET相关

Sample Image - ajaxtreeview.gif

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 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 using the current AJAX technique,(in it’s simplest way) to implement an on demand tree view. Since XML is common standard and easy to implement I am using XML in my sample application rather than any database. I have found another article here that to build a tree view using this 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. By creators’ opinion, this should have improved customers’ 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. But several years later, the technology has been reborn with new browsers 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 ready made frameworks are also available on the internet like Microsoft AJAX/ATLAS , Enterprise AJAX are few of them.

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 levels-children) and rendering into the browser takes quite long time. After attempting 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 is AJAX is the best bet. By this we could avoid a post back and flickering of the browser rather 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 using a style sheet and some JavaScript all together give some real effects. On Page Load or any 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 (off 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.

<?xml version="1.0" encoding="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 contain all the required methods to handle the asynchronous calls and standard AJAX methods. Java script is the core component in this technology as you can see. It handles the change detection, data request receipt, and placing the data on the page.

 

//To toggle the node image and expand collapse

function Toggle(node){

 

      // Unfold the branch if it isn't visible

      if (node.nextSibling.style)   {          

            if (node.childNodes.length > 0)     {

                  if (node.childNodes.item(0).nodeName == "IMG"){

         ...

 

The core function for the asynchronous request is

//The core function to get the xml http request object

function GetXmlHttpObject(){

      var objXMLHttp=null

      if (window.XMLHttpRequest){

        ...

 

The HTML will looks 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 be call the following function to invoke the server request

/***********************************************************

//Builds the query string and invoke a request to the server

//using javascript async call

/***********************************************************/

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 look nice. You can build that section also 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 are processing this code behind and renders into the browser. When the client http request is made the following scripts will execute on the server and renders the HTML on the browser.

private void Page_Load(object sender, System.EventArgs e)

{          

if (!IsPostBack)

 {

 

//id passed thro' the url query string

string key = Request.QueryString["q"];

 

if (key != null)

{

      //read the xml tree file from the web.config file

      //add the following key in web.config

      //<appSettings>

      //<add key="XmlTree" value="~/TreeSource.XML" />

      String path = Server.MapPath(ConfigurationSettings.AppSettings["XmlTree"]);

 

      //I use XmlDocument object here to manipulate Xml- You can use other objects

      //You can cache the XmlDocument.OuterXml string

      XmlDocument xmlTree = new XmlDocument();

      xmlTree.Load(path);

      System.IO.StringReader xmlSR = new System.IO.StringReader(xmlTree.OuterXml);

 

      //If you want to use database driven tree you skip above codes

      //but the columns should be there in the data table

      DataSet ds = new DataSet();

      ds.ReadXml(xmlSR);

      DataView dv = ds.Tables[0].DefaultView;

 

      //filter for the parent

      dv.RowFilter = " ParentID = '" + key + "'";

 

      //render the brower with a <UL> tag and <LI> list

      //I have used some styles

      Response.Write ("<ul class='wTreeStyle'>");

 

      //write all the children here

      for(int i=0; i < dv.Count; i++)

      {    

            //formatted <LI> tag -

            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 the simplicity, I am putting only the required codes since I want to share the implementation, you can customize or enhance in your projects.

Conclusion:

This article is aimed to illustrate the simplicity of using the AJAX technology in any ASP.NET application. It is up to the 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. Currently I tested the application in MS Visual Studio V.7/ MDE 2003 and MS .NET Framework 1.1. And C# - ASP.NET.

Credits:

只有注册用户登录后才能发表评论。