public void AsyncTree()
{
string root = Request.Params["root"];
int parentID = 0;
Tree objTree = new Tree();
//select all the nodes - you can make it more efficient by
//storing the datatable Cache to avoid frequent requests to DB
DataTable dtNodes = objTree.Select(0);
if (root == "source") //for the first time the JQuery tree will send the root param value as "source"
{
GenerateTree(dtNodes, 0);
}
else if (int.TryParse(root, out parentID)) //subsequent requests will send the ID
{
if (parentID > 0)
{
GenerateTree(dtNodes, parentID);
}
}
}
private void GenerateTree(DataTable dtParent, int parentID)
{
System.Text.StringBuilder tree = new System.Text.StringBuilder();
DataView dv = new DataView(dtParent);
dv.RowFilter = string.Format("ParentNodeID = {0}", parentID);
tree.Append("[");
//loop through each leaf
for (int i = 0; i < dv.Count; i++)
{
tree.Append("{");
tree.Append(""text": "").Append(dv[i]["Title"]).Append("",");
tree.Append(""id": "").Append(dv[i]["TreeNodeID"]).Append("",");
//check whether this node has child nodes
DataView dvChild = new DataView(dtParent);
dvChild.RowFilter = string.Format("ParentNodeID = {0}", dv[i]["TreeNodeID"]);
if (dvChild.Count > 0) //if so mark it in the return node array
tree.Append(""hasChildren": true");
tree.Append("},");
}
//remove the ending comma from the result
if (tree.Length > 1)
{
tree = tree.Remove(tree.Length - 1, 1);
}
tree.Append("]");
//put the result in Response and end the Response
Response.Write(tree.ToString());
Response.End();
}