Click here to Skip to main content
12,552,615 members (53,660 online)
Click here to Skip to main content
Add your own
alternative version


45 bookmarked

An Example to Use jQuery Template

, 4 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
This article presents a working example of how to use the jQuery template.


This article presents a working example of using a jQuery template.


Recently I got a chance to try the jQuery template. The jQuery template is a JavaScript library that helps to transfer JSON data into HTML content. According to this link, it was developed by Microsoft ASP.NET team in collaboration with the open-source jQuery team and it was intended to be included in the jQuery core library (the jQuery.js library) when jQuery 1.5 is released. By the time when I tried it, jQuery had already advanced to version 1.9.1, but I still could not see it included. At least I could not find anything related to jQuery template in jQuery's official documentation. So if you want to try it, you will need to download jquery.tmpl.js or jquery.tmpl.min.js from its own website. Following its website, you can find some basic documentation on how to use the jQuery template. This article mainly provides you a running example of using a jQuery template. If you are more interested in reading some instructional document, you can take a look at jQuery template's website.

The example is developed in an ASP.NET MVC 2 web application in Visual Studio 2010. I am fully aware that ASP.NET MVC has already gone through versions 3 and 4. But I am also aware that not all readers are using these higher versions. Hopefully by keeping the version low, I can make all readers' life easy if they do want to download the application and try it out themselves.

The example application has the following components:

  • The Models\CheckBoxModel.cs file is the application's data model; 
  • The Controllers\HomeController.cs file is the MVC application's controller; 
  • The Views\Home\Index.aspx file is the MVC application's only view;
  • The Content\Site.css file has some CSS styles used by the application.
Of course, we will need jQuery's core library jquery-1.9.1.min.js and jquery.tmpl.min.js files. In this article, I will first show you the data model, and then show you how to display the data on the web browser using the jQuery template. 

The Data Model  

The application's data model is implemented in the Models\CheckBoxModel.cs file:

using System;
using System.Collections.Generic;
namespace jQueryTemplate.Models
    public class CheckBoxModel
        public int Id { get; set; }
        public string Text { get; set; }
        public bool Checked { get; set; }
        public List<CheckBoxModel> Children { get; set; }
    public static class CheckBoxRepository
        private static List<CheckBoxModel> CheckBoxes { get; set; }
        public static void Initiate()
            CheckBoxes = new List<CheckBoxModel>();
            const int count1 = 10, count2 = 10, count3 = 20;
            var idSeed = 1000000;
            for (var i = 1; i <= count1; i++)
                var ckBoxTier1 = new CheckBoxModel
                    Id = ++idSeed,
                    Text = "Item No." + i,
                    Checked = idSeed % 2 != 0,
                    Children = new List<CheckBoxModel>()
                if (i % 2 == 0) { continue; }
                for (int j = 1; j <= count2; j++)
                    var ckBoxTier2 = new CheckBoxModel
                        Id = ++idSeed,
                        Text = "Item No." + i + "." + j,
                        Checked = idSeed % 2 != 0,
                        Children = new List<CheckBoxModel>()
                    if (j % 2 == 0) { continue; }
                    for(var k = 1; k <= count3; k++)
                        var ckBoxTier3 = new CheckBoxModel
                            Id = ++idSeed,
                            Text = "Item No." + i + "." + j + "." + k,
                            Checked = idSeed % 2 != 0,
                            Children = new List<CheckBoxModel>()
        public static List<CheckBoxModel> GetCheckBoxes()
            return CheckBoxes;
The purpose of this example application is to load a set of data points organized in tree structures from the server and display them as checkboxes.  
  • The CheckBoxModel class represents a checkbox. It can optionally contain some other checkboxes in its "Children" list;
  • The CheckBoxRepository serves as the repository of the set of checkboxes. The Initiate method initiates the set, and we can access this set through the GetCheckBoxes method. You can see from the code that the trees are of three layers. Some of the checkboxes are checked and some are not checked. Some of the checkboxes have children and some do not have children. 

The Controller 

The MVC application's controller is implemented in the Controllers\HomeController.cs file:

using System.Web.Mvc;
using jQueryTemplate.Models;
namespace jQueryTemplate.Controllers
    public class HomeController : Controller
        public ActionResult Index()
            // Initiate checkboxes
            return View();
        public ActionResult GetCheckBoxesData()
            return Json(CheckBoxRepository.GetCheckBoxes());
  • The Index method loads the Views\Home\Index.aspx view. It also initiates the set of checkbox trees; 
  • The GetCheckBoxesData method returns the set of checkbox trees in JSON format, which will be accessed by AJAX calls from the view. 

The View 

The MVC application's view is implemented in the Views\Home\Index.aspx file:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" >
<head runat="server">
    <title>jQuery Template Example</title>
    <link type="text/css" rel="stylesheet"
        href="<%=Url.Content("~/Content/Site.css") %>" />
    <script type="text/javascript"
    <script type="text/javascript"
<script type="text/javascript">
    $(document).ready(function () {
        var addCheckBoxesToDom = function (chkBxData) {
            var div = $('#divCheckBoxes');
            $('a.toggle', div).click(function () {
                var t = $(this);
                var ul = t.closest('li').children('ul');
                if (t.hasClass('opened')) {
                } else {
                return false;
        $('#btnLoadCheckBoxes').click(function () {
            var url = '<%=Url.Action("GetCheckBoxesData", "Home") %>';
                url: url,
                type: "POST",
                cache: false
            }).done(function (data) {
                var chkBxData = { items: data };
        $('#btnClearCheckBoxes').click(function () {
    <div style="width: 450px">
            <span><a id="btnLoadCheckBoxes" href="#" class="linkbutton">
                      Load checkboxes</a></span>
            <span><a id="btnClearCheckBoxes" href="#" class="linkbutton">
                      Clear checkboxes</a></span>
        <div id="divCheckBoxes" />
<script id="checkBoxTemplate" type="text/html">
{{each items}}
    {{if Children.length > 0}}<a href="#" class="toggle" />{{/if}}
    <label{{if Children.length == 0}} class="static"{{/if}}>
        <input type="checkbox" id="ck${Id}"{{if Checked}}
        checked="checked"{{/if}} />[${Id}]-${Text}</label>
        {{if Children.length >

In this file, I have added the following contents:

  • Two buttons btnLoadCheckBoxes and btnClearCheckBoxes. The btnLoadCheckBoxes button initiates an AJAX call to load the checkbox data in JSON format. Upon a successful AJAX call, it translates the JSON data into HTML content through the jQuery template. The HTML content is then inserted into the divCheckBoxes "div". The btnClearCheckBoxes button clears the content inserted into the divCheckBoxe "div". 
  • checkBoxTemplate is the template. The jQuery template uses this template to translate the JSON data into HTML content using the "$('#checkBoxTemplate').tmpl(chkBxData)" syntax, where chkBxData is the JSON data. 
The MVC application is complete, we can now test run it. 

Run the Application 

When the application first launches, we can see the two buttons that I put in the Views\Home\Index.aspx view.

Click on the "Load checkboxes" button, an AJAX call is made to retrieve the JSON data of the checkbox trees and the jQuery template is used to transfer the JSON data into the desired HTML content. The HTML content is then shown in the web page.

If a checkbox has children, you can expand the node and see the three layer tree structure.

The checkbox trees are implemented by an HTML "<ul>". In case you are interested, the following are the CSS styles that implemented in the Content\Site.css file. These CSS styles turn the <ul> into expandable trees with some help from JavaScript.

/* Checkbox tree */
    border-style: solid;
    border-width: 2px 1px 1px;
    border-color: #F05D23 #797979 #797979;
    margin-top: 5px;
    padding: 0px;
    width: 100%; 
    max-height: 500px;
    overflow-x: hidden;
#divCheckBoxes ul
    margin: 0px; padding: 0px;
#divCheckBoxes li
    padding: 0px 0px 6px 0px;
    list-style: none outside none;
#divCheckBoxes li>span 
    border-bottom: 1px dotted #CCCCCC;
    padding: 2px;
    display: block;
#divCheckBoxes li>span>label.static {
    margin-left: 15px
#divCheckBoxes li>span.tierTwo {
    padding-left: 30px
#divCheckBoxes li>span.tierThree {
    padding-left: 70px
    background: url("images/ToggleClose.png") no-repeat scroll 3px 6px transparent;
    padding-left: 15px;
    text-decoration: none;
    vertical-align: top
    background: url("images/ToggleOpen.png") no-repeat scroll 3px 6px transparent;

Points of Interest 

  • There are many methods to generate HTML content through JavaScript. Without any external help, you can actually write your own code to generate the HTML content, which may normally be the most efficient way if you have a good understanding of the DOM structure. But if you are not very confident on your understanding of the DOM and you do want to have some external help, you can create a template and use the jQuery template jquery.tmpl.min.js to generate the HTML content.
  • If you just want to use AJAX to load data into your web pages, you can actually consider a partial view. I have an early article Load Clean HTML Fragments using jQuery and MVC to show you how to load partial views into web pages with AJAX calls. The advantage of using partial views is that they can be embedded in other MVC views directly and loaded by AJAX calls as well. Reusability is a huge advantage of partial views over the jQuery template. 
  • In any case, the jQuery template can prove to be useful in some situations. If you are interested in exploring jQuery template, this article is a running example and may be of some use for you.
  • I hope that you like my postings and I hope that this article can help you one way or the other.  


  • First revision - 3/9/2013.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Dr. Song Li
United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

You may also be interested in...


Comments and Discussions

QuestionWhy did not, at least in MVC 3? Pin
Oscar Onorato15-Nov-14 6:21
memberOscar Onorato15-Nov-14 6:21 
GeneralMy vote of 5 Pin
manoj kumar choubey19-Aug-13 23:26
membermanoj kumar choubey19-Aug-13 23:26 
QuestionDeprecated Pin
mauricitoia7-May-13 5:48
membermauricitoia7-May-13 5:48 
AnswerRe: Deprecated Pin
mohamed fahmy19-Mar-14 18:02
membermohamed fahmy19-Mar-14 18:02 
GeneralRe: Deprecated Pin
Dr. Song Li20-Mar-14 3:51
mvpDr. Song Li20-Mar-14 3:51 
GeneralMy vote of 5 Pin
Mihai MOGA12-Apr-13 19:17
memberMihai MOGA12-Apr-13 19:17 
GeneralRe: My vote of 5 Pin
Dr. Song Li13-Apr-13 3:51
memberDr. Song Li13-Apr-13 3:51 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun5-Apr-13 1:22
memberHumayun Kabir Mamun5-Apr-13 1:22 
GeneralMy vote of 5 Pin
Prasad Khandekar4-Apr-13 10:24
memberPrasad Khandekar4-Apr-13 10:24 
GeneralMy vote of 5 Pin
Abinash Bishoyi4-Apr-13 7:38
memberAbinash Bishoyi4-Apr-13 7:38 
GeneralMy vote of 5 Pin
Jerry OLoughlin23-Mar-13 17:34
memberJerry OLoughlin23-Mar-13 17:34 
GeneralRe: My vote of 5 Pin
Dr. Song Li23-Mar-13 17:59
memberDr. Song Li23-Mar-13 17:59 
QuestionNice Pin
aankur8110-Mar-13 2:13
memberaankur8110-Mar-13 2:13 
AnswerRe: Nice Pin
Dr. Song Li10-Mar-13 5:08
memberDr. Song Li10-Mar-13 5:08 
GeneralMy vote of 4 Pin
Olcay Seker10-Mar-13 1:34
memberOlcay Seker10-Mar-13 1:34 
GeneralRe: My vote of 4 Pin
Dr. Song Li10-Mar-13 5:07
memberDr. Song Li10-Mar-13 5:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161021.1 | Last Updated 4 Apr 2013
Article Copyright 2013 by Dr. Song Li
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid