CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Creating a Simple AJAX Master-Details View Using jQuery, JSON and jTemplates in ASP.Net

By Satheesh Babu
Posted On Mar 29,2009
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 15
Category: jQuery/ASP.Net
Print this article.

Creating a Simple AJAX Master-Details View Using jQuery, JSON and jTemplates in ASP.Net

 

My previous article - Building Cascading DropDownList in ASP.Net Using jQuery and JSON discussed about using jQuery and JSON communication to implement Cascading DropDownList control. Clearly, with jQuery and JSON we can prevent need of UpdatePanel control which is really bulky when compared to jQuery Ajax communication. In this article, we will try to implement an yet another Ajax enabled functionality with jQuery and JSON.

There will be situations where we need to display a tabular data to users based on some inputs in ASP.Net application. We will see how this can be addressed with jQuery and JSON to build a tabular data display in ASP.Net page. Ideally, this can be done by iterating the JSON resultset and constructing a HTML table using jQuery. But,in this article, we will do the same with the help of a jQuery plug-in called jTemplate.

What is jTemplate?

jTemplate is a simple JavaScript template engine which can be used to present data in tabular format. jTemplate provides language oriented features like conditional statements, loops, etc for building up templates. You can visit the jTemplate site here.

 

Steps to integrate the jTemplate in your Project

1.      Download the latest version of jTemplate plug-in either from jTemplate site or jQuery site.

2.      Copy the plug-in to your solution and link it through script tag.

<script src="_scripts/jquery-jtemplates.js" type="text/javascript"></script>

 

Integrating jQuery

Download the latest JQuery library from JQuery.com and include the reference to the JQuery library file in our ASPX page.

<script src="_scripts/jquery-1.2.6.js" type="text/javascript">

I have copied the jquery library into _scripts folder in the solution. To know more and to setup jQuery intellisense in Visual studio 2008, please follow my article - Using JQuery in ASP.Net AJAX Applications – Part 1


Moving forward, we will see how to implement a simple Master-Details view using jQuery, JSON and jTemplate. We will have a DropDownList control that lists all departments in a company. On selection of a department in the DropDownList we will list all the employees in that department in tabular form.

Refer the below diagram,

 CodeDigest.Com 

To build this, we will build an HttpHandler that can give back the list of employees in JSON format by accepting the department as a query string parameter. To display the list of employee, we will build template and apply the template to display the JSON data using jQuery. 

 

Constructing Master-Details View

1.      Open Visual Studio 2008, Click File >Website and choose ASP.Net Website. Integrate jQuery and jTemplate library into your site as mentioned in the previous section.

2.      Drag DropDownList control from the toolbox and rename its ID to ddlDepartment.

3.      For simplicity purpose, I will hard code the departments available. You can bind it from database in your case.

<asp:dropdownlist ID="ddlDept" runat="server">

     <asp:ListItem Value="0">Select</asp:ListItem>

    <asp:ListItem>IT</asp:ListItem>

    <asp:ListItem>ECE</asp:ListItem>

    <asp:ListItem>MEC</asp:ListItem>

     <asp:ListItem>CSE</asp:ListItem>

    </asp:dropdownlist>

 

4.      Next, we will build an HttpHandler that can return back list of employees in a department in JSON format. To do this, Right click the project in solution and click “Add New Item”. Select “Generic Hanlder”. I have named as GetEmployees.ashx.

 

<%@ WebHandler Language="C#" Class=" GetEmployees" %>

 

using System;

using System.Web;

using System.Data;

using System.Text;

using System.Data.SqlClient;

using System.Configuration;

 

public class GetEmployees: IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

        string dept = context.Request.QueryString["Dept"];

        string query = "SELECT * FROM [Employee] WHERE Department='" + dept + "'";

        DataTable dt = GetDt(query);

        StringBuilder strStudents = new StringBuilder();

 

        if (dt != null)

        {

            strStudents.Append("{ employees:[");

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

            {

                strStudents.Append("{");

                strStudents.Append("\"EmployeeID\":\"" + dt.Rows[i]["EmpID"].ToString() + "\",");

                strStudents.Append("\"EmployeeName\":\"" + dt.Rows[i]["EmpName"].ToString() + "\",");

                strStudents.Append("\"Department\":\"" + dt.Rows[i]["Department"].ToString() + "\",");

                strStudents.Append("\"Age\":\"" + dt.Rows[i]["Age"].ToString() + "\",");

                strStudents.Append("\"Address\":\"" + dt.Rows[i]["Address"].ToString() + "\"");

                if (i != dt.Rows.Count - 1)

                {

                    strStudents.Append("},");

                }

            }

        }

        strStudents.Append("}");

        strStudents.Append("]}");

        context.Response.ContentType = "application/json";

        context.Response.ContentEncoding = Encoding.UTF8;

        context.Response.Write(strStudents.ToString());

        context.Response.End();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

    public DataTable GetDt(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dt = new DataTable();

        ada.Fill(dt);

        return dt;

    }

}

 

I have created the JSON data format through my code. If you have ASP.Net AJAX installed on the server you can try using JavaScriptSerializer class packed in System.Web.Script.Serialization namespace to convert objects to JSON format.

 




5.      Next, we will build the template with the jTemplate plug-in. Since, we are displaying the data in a simple tabular format we will build a simple template with table tag and for-each loop in jTemplate.

<table>

  <thead>

    <tr style="background-color:Maroon;color:White;">

      <th>Employee ID</th>

      <th>Employee Name</th>

      <th>Department</th>

      <th>Age</th>

      <th>Address</th>    

    </tr>

  </thead>

  <tbody>

   {#foreach $T.employees as record}

    <tr>

      <td>{$T.record.EmployeeID}</td>

      <td>{$T.record.EmployeeName}</td>

      <td>{$T.record.Department}</td>

      <td>{$T.record.Age}</td>

     <td>{$T.record.Address}</td>              

    </tr>

    {#/for}

  </tbody>

</table>

 

The above template is written in a separate file called temp.htm in the solution.

 

6.      To Display the data, we need to specify a container which can hold the tabular data when the template is applied. 

Finally, our aspx will look like,

<form id="form1" runat="server">

    <div>   

    Department: <asp:dropdownlist ID="ddlDept" runat="server">

     <asp:ListItem Value="0">Select</asp:ListItem>

    <asp:ListItem>IT</asp:ListItem>

    <asp:ListItem>ECE</asp:ListItem>

    <asp:ListItem>MEC</asp:ListItem>

     <asp:ListItem>CSE</asp:ListItem>

    </asp:dropdownlist>

    </div>

    Employees:

    <div id="dvDetails">

    </div>

    </form>

 

The DIV “dvDetails” is our container DIV where our data will be rendered in table format.

 

7.      Finally, we will make the AJAX call using jQuery on onchange event of the dropdown and apply the template with JSON data that is returned back from the server.

<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>

    <script src="_scripts/jquery-jtemplates.js" type="text/javascript"></script>

    <script language="javascript">

        $(document).ready(function() {

            $("#ddlDept").change(function() {

                var DeptID = $("#ddlDept > option[@selected]").attr("text");

                if (DeptID != 0) {

                    $.getJSON('GetEmployees.ashx?Dept=' + DeptID, function(employees) {

                     //Set and Apply template                

                        $('#dvDetails').setTemplateURL('temp.htm');

                        $('#dvDetails').processTemplate(employees);

                    });

                }

            });

        });

    </script>

Execute the page. You can see Master-Details view in action without using ASP.Net AJAX.

Download the source attached with article to see it inaction.

 

Downloads

Download Source 

Conclusion

Thus, we have seen how to build a simple master details view using jQuery and jTemplate plug-in.  This technique can be used as an alternative to ASP.Net AJAX approach for more performance improvements. Download the source attached with this article and see it in action.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
error in JSON
I found this helpful but I think there is an error in the JSON generated:
strStudents.Append("{ employees:[");
needs quotes around eployees so it should read:
strStudents.Append("{ \"employees\":[");
jquery templates
thanks for share.
Excellent!
Had been looking around for such a tutorial. Thank you! :)
vbnvb
bn
Another example showing the use of WCF with JSON and jTemplates
Very interesting article.

Ive just written a similar tutorial explaining how to create a WCF service exposing JSON and displaying the data with jTemplates.

on: http://yoavniran.wordpress.com/2009/06/26/tying-in-wcf-json-and-jtemplates/
good
good
Detailed Article
Another detailed article related to this topic can be found at
<a href="http://smallworkarounds.blogspot.com/2009/02/jquery-aspnet-how-to-implement.html">http://smallworkarounds.blogspot.com/2009/02/jquery-aspnet-how-to-implement.html</a>
Thanks
Thanks for the feedback guys!
@Balaji,
I have not written one. Will let you know if i post.
@Variant,
Thanks for pointing out that. Yeah..i accept the code is prone to SQL injetcion attack(like you said, since it i's jus a sample i was bit lazy :) ). You can use Parameterised query or SP's to prevent it.
@Paul Speranza,
Yes you can also do this requirement with pagemethod also. I took it
http://trephine.org
Wow, I hadn't thought about it that way before. Good write up, very clearly written. Have you written previously about AJAX master details? I'd love to read more.
SQL Injection
Sure it's only a sample but the handler has a screaming SQL Injection vulnerability.
A question
Satheesh,

Is there any reason you didn't just create webmethods on the page instead of the handler?
More..
Hello again...

I disagree with Enhancement, I prefer the the manual approach of JSON.
Wonderful
I love this, so simple but so clever. I just love the way how you did the json through a handler. Perfect!!
great
good article,thank u.
Enhancement
I've used very similar technique but instead of creating Json manually you can use start Json converter and convert the datatable to json. This is more flexible approach.