Click here to Skip to main content
Click here to Skip to main content

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.

Introduction

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

Background    

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>()
                };
                CheckBoxes.Add(ckBoxTier1);
                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>()
                    };
                    ckBoxTier1.Children.Add(ckBoxTier2);
                    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>()
                        };
                        ckBoxTier2.Children.Add(ckBoxTier3);
                    }
                }
            }
        }
        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
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            // Initiate checkboxes
            CheckBoxRepository.Initiate();
            return View();
        }
        [HttpPost]
        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"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>jQuery Template Example</title>
    <link type="text/css" rel="stylesheet"
        href="<%=Url.Content("~/Content/Site.css") %>" />
    <script type="text/javascript"
        src="<%=Url.Content("~/Scripts/jquery-1.9.1.min.js")%>"></script>
    <script type="text/javascript"
        src="<%=Url.Content("~/Scripts/jquery.tmpl.min.js")%>"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var addCheckBoxesToDom = function (chkBxData) {
            var div = $('#divCheckBoxes');
            div.html($('#checkBoxTemplate').tmpl(chkBxData));
            $('a.toggle', div).click(function () {
                var t = $(this);
                var ul = t.closest('li').children('ul');
                if (t.hasClass('opened')) {
                    t.removeClass('opened');
                    ul.hide();
                } else {
                    t.addClass('opened');
                    ul.show();
                }
                return false;
            });
        };
        $('#btnLoadCheckBoxes').click(function () {
            var url = '<%=Url.Action("GetCheckBoxesData", "Home") %>';
            $.ajax({
                url: url,
                type: "POST",
                cache: false
            }).done(function (data) {
                var chkBxData = { items: data };
                addCheckBoxesToDom(chkBxData);
            });
        });
        $('#btnClearCheckBoxes').click(function () {
            $('#divCheckBoxes').html('');
        });
    });
</script>
</head>
<body>
<div>
    <div style="width: 450px">
        <div>
            <span><a id="btnLoadCheckBoxes" href="#" class="linkbutton">
                      Load checkboxes</a></span>
            <span><a id="btnClearCheckBoxes" href="#" class="linkbutton">
                      Clear checkboxes</a></span>
        </div>
        <div id="divCheckBoxes" />
    </div>
</div>
</body>
<script id="checkBoxTemplate" type="text/html">
<ul>
{{each items}}
    <li>
    <span>
    {{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>
    </span>
        {{if Children.length > 0}}
        <ul style="display: none">
        {{each Children}}
        <li>
        <span class="tierTwo">
            {{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>
        </span>
            {{if Children.length > 0}}
            <ul style="display: none">
            {{each Children}}
            <li>
            <span class="tierThree">
                <label><input type="checkbox" id="ck${Id}"{{if Checked}}
                    checked="checked"{{/if}} />[${Id}]-${Text}</label>
            </span>
            </li>
            {{/each}}
            </ul>
            {{/if}}
    </li>
    {{/each}}
    </ul>
    {{/if}}
    </li>
{{/each}}
</ul>
</script>
</html>

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 */
#divCheckBoxes 
{
    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
}
a.toggle 
{
    background: url("images/ToggleClose.png") no-repeat scroll 3px 6px transparent;
    padding-left: 15px;
    text-decoration: none;
    vertical-align: top
}
a.toggle.opened 
{
    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.  

History

  • First revision - 3/9/2013.

License

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

Share

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.

Comments and Discussions

 
QuestionWhy did not, at least in MVC 3? PinmemberOscar Onorato15-Nov-14 7:21 
GeneralMy vote of 5 Pinmembermanoj kumar choubey20-Aug-13 0:26 
QuestionDeprecated Pinmembermauricitoia7-May-13 6:48 
AnswerRe: Deprecated Pinmembermohamed fahmy19-Mar-14 19:02 
GeneralRe: Deprecated PinmvpDr. Song Li20-Mar-14 4:51 
GeneralMy vote of 5 PinmemberMihai MOGA12-Apr-13 20:17 
GeneralRe: My vote of 5 PinmemberDr. Song Li13-Apr-13 4:51 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun5-Apr-13 2:22 
GeneralMy vote of 5 PinmemberPrasad Khandekar4-Apr-13 11:24 
GeneralMy vote of 5 PinmemberAbinash Bishoyi4-Apr-13 8:38 
GeneralMy vote of 5 PinmemberJerry OLoughlin23-Mar-13 18:34 
GeneralRe: My vote of 5 PinmemberDr. Song Li23-Mar-13 18:59 
QuestionNice Pinmemberaankur8110-Mar-13 3:13 
AnswerRe: Nice PinmemberDr. Song Li10-Mar-13 6:08 
GeneralMy vote of 4 PinmemberOlcay Seker10-Mar-13 2:34 
GeneralRe: My vote of 4 PinmemberDr. Song Li10-Mar-13 6:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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.141216.1 | Last Updated 4 Apr 2013
Article Copyright 2013 by Dr. Song Li
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid