Introduction
This is the sample code which uses AJAX.NET and JavaScript to build treeview on the fly. It allows to add, edit and delete tree nodes. It also demonstrates how to using UpdatePanel
to refresh from the client side.
Background
If we want to generate a treeview which gives us more flexibility and control in each part of the functionality, then we can use this code.
Using the Code
Pre-requisite for this code is VS2005, SQL2000 and AJAX.NET (with DLL System.Web.Extensions, Version=1.0.61025.0). Please use the DB script available in App_Data folder which creates the table and stored procedure required for this demo.
We need to define a DIV
place holder for Treeview
so that it will not stretch or generate scroll bars when the tree grows:
<div style="height:200px; width:300px; overflow-y:scroll;"></div>
We need a Root node from where we can start building our tree, this is not editable and deletable. This is the only static
node and rest of the children are going to be of the same structure and will be included on the fly. "displayMenu(0, 'Root')
" displays the context menu, "0
" represents the categoryid or treenode DB ID. It will be greater than 0 (Zero) in case of child nodes. Rest of the processing will be the interaction of webservice and updating the Grid.
<table width="100%" id="tblRoot">
<tr valign='top'>
<td width="20px"><img src="Images/Plus.gif"
id="img_1" title="Expand"
border="0" onClick="CollapseOrExpand(this, 0, 'Root');"/></td>
<td oncontextmenu="displayMenu(0, 'Root');return false;">Root</td>
</tr>
</table>
The below code is required to call the webservice from the client side:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/TreeViewWS.asmx" />
</Services>
</asp:ScriptManager>
To update the gridview
when we make any modifications to the grid, we need to refresh the updatepanel
in which we included the gridview
. This can be triggered by using the following JavaScript code.
__doPostBack(HdnCurrentFileID, '');
As we already have triggers in updatepanel
for this hidden variable, this will postback the panel and refresh the grid.
Points of Interest
The most fun and worst part is handling the JavaScript errors that we will get while coding, especially when our web method is throwing exceptions, use the "debugger
" keyword to quickly debug the JavaScript code.
Generating the context base and passing the respective node details like Id, Desc will be fun.
Last but not least, AJAX Webservice call and updatepanel which refreshes the grid will be worth mentioning as it eases a lot of the coding effort.
HATS OFF TO AJAX!