Using jQuery tree for database data

Posted on May 22, 2009

Hi,

This blog post is actually to answer a really nice guy from a forum (.Net) I run in Hebrew, but I thought it will be really nice to write about it in general.

I get lots of questions regarding the concept of using jQuery (in general) with .net and database data.

I actually blame Microsoft for having the tutorials in their website teaching only SqlDataSource, which I never used and recommend that you don’t use too.

So, the majority of the questions I get are not at all about code. They are all about concept: How to communicate with data, How to retrieve data and more.

Ok, so this tutorial is all about jQuery, LINQ to Sql, and the jQuery tree. The only difference is that I’m not going to display files in folders, but pages from a Sql table, every page has a “ParentID” fields, so it will be very easy to understand.

This tutorial is also to clarify you can use the tree for any relational database or file data.

So, Let’s Start!

First, let’s go and download the 2 packages.

jQuery

jQuery File Tree

After downloading the 2 packages, we’ll open up a new website in Visual Studio.

Our files should look like this:

**What do we have here?

**

Well, we have all the css from the jQuery file tree library, we have the Images also from this library, we have the js files from: jQuery, jQuery file tree and another js file which we created for our custom functions.

Alright, now let’s create our page:

We have all the script file and css files in our page. Also, we wrote a div called “myFirstTree” in our page, this div will hold our tree.

What else do we need?

Well, like I said, we are displaying database data here, so let’s create a very simple database with one table, also we will create a LINQ mapping file for it.

B.T.W, you can use any kind of data access, you can use nHibernate, or whatever you may find comfortable for your use.

I use linq for this example, don’t ask why, just felt like it

So, we have these fields:

pageID – Identity field

pageName

pageParentID

Let’s create our data, just randomly fill our table with some data, and then we can go back and retrieve it from the client side using some jQuery.

So, we have our data. I don’t think i need to further explain this no?

Now, let’s write some js code to retrieve the data from the server for us.

Our js code should look like this:

[javascript]

$(document).ready(function() {

$(‘#myFirstTree’).fileTree({

root: ‘0’,

script: ‘jQueryTreeHandler.ashx’,

multiFolder: true,

loadMessage: ‘Tree loading…’

}, function(file) {

alert(file);

});

});

[/javascript]

Let’s explain this code a bit shall we?

First, we chose our pre crated div “myFirstTree”. Then we initialized the fileTree object with these parameters:

root: the first parameter that will be passed to our Handler

script: our path to the handler

multiFolder: whether our tree will be multi folder or not, when this is false, clicking each folder will collapse all the other folders in the tree.

loadingMessage: this message will be displayed when data is being retrieved from the server.

fileFunction: this function will be fired when a file from the tree is selected.

All pretty straight forward up until now, let’s go on and create our handler:

The parameter we know is passed in is called “dir”, so that is what we will use here.

So, this is what your handler code should look like:

[csharp]

<%@ WebHandler Language=“C#” Class=“jQueryTreeHandler” %>

using System;

using System.Web;

using System.Linq;

public class jQueryTreeHandler : IHttpHandler {

public void ProcessRequest (HttpContext context) {

context.Response.ContentType = “text/plain”;

int parentID = Convert.ToInt32(context.Request.Form[“dir”]);

string list = “";

jQueryTreeDataContext db = new jQueryTreeDataContext();

var pages = from p in db.Pages

where p.pageParentID == parentID

select p;

foreach (Page item in pages)

{

list += String.Format("<li class="directory collapsed"><a href="#" rel="{0}">{1}”, item.pageID.ToString(), item.pageName);

}

context.Response.Write(String.Format("<ul class="jqueryFileTree" style="display: none;">{0}", list));

}

public bool IsReusable {

get {

return false;

}

}

}

[/csharp]

Comment: I didn’t take care of a situation where a row has no children, it wasn’t necessary for my example. However, in real life code you should, and if a row does not have any children, you shouldn’t display a folder, but a file instead.

And this is how our code looks like in the final result (Html output):

Comment: I had to tweak the jQuery file tree code in order for it to work with database data. Normally it has a regullar expression validating the “rel” attribute actually contains data with “/”, that needed to be changes.

I uploaded the file to here for you, so download away…

[download id=”2″]