Click here to Skip to main content
16,016,760 members
Articles / Web Development / ASP.NET

Client Templating with jQuery

Rate me:
Please Sign up or sign in to vote.
4.96/5 (60 votes)
15 Nov 2010CPOL6 min read 183.5K   1.8K   152   72
This article discusses a very cool feature of jQuery that is Client Templating

Table of Contents

Introduction

jQuery templating is becoming a new buzzword for the new Web applications. One cannot avoid jQuery in web applications. Currently, most of the applications are using jQuery heavily. It provides a very good look & feel and better performance.

A lot of plugins are also available for jQuery, they provide really cool features. We can provide a very new and trendy look and feel with the help of jQuery. Also, as we are making very rich applications, performance is also becoming a key point for our applications. jQuery helps a lot in this regard also. We will be discussing mainly jQuery Templating in this article.

What is jQuery

jQuery is a JavaScript library that works on top of the JavaScript. jQuery provides a very simple way for HTML document traversing, DOM manipulation, event handling, animating, and Ajax interactions for rapid web development. That could have been very complex while working with normal JavaScript.

jQuery is becoming more and more popular day by day. It was even integrated with VS2008 and also available with VS2010. jQuery is open source. Due to its features, Microsoft started to support jQuery team and also working with them, to provide better web based tools to their Clients.

Prerequisites

  • jQuery library
  • A plugin for templating
  • JSON library

jQuery already comes with VS2008/2010. But if you are working with VS 2005, then you can download from the following link.

To download plugin for templating feature, click here.
Relax guys!! You won't need this plugin after jQuery 1.5. This would be integrated with the main library itself. :)

To download JSON library, click here.

jQuery Templating

As we are working on Client server architecture, most of the things are done by the server itself. Server sends the HTML response to the browser and the browser just display it. Earlier, we were not doing a lot of things at the client side, Normally, some validation and a little bit more at client side. With the help of Ajax call from client side and retrieving data in a very convenient format in JSON, it really becomes easy, to start moving server side code to Client side. This means the data travelling from server to client is not the whole HTML response but it is just data that we have to show in different HTML controls.

Let's see an pictorial overview:

Client Templating

Figure: How Client Templating works

Templates

To use client templating, you need the following:

  • First, data at client side
  • Client side template
  • Now with the help of jQuery, make the HTML elements and adding it to the DOM.

Now I am explaining one example. A sample is attached with this article.

In my example, I am displaying a list of Persons and also adding a Person later.

Displaying Data

So here, first I am showing the details of Persons. The data is coming in JSON format with the help of Ajax call, in document.ready function.

Let's move step by step:

I have created a Client template to display the person data.The template is:

XML
<script type="text/html" id="personTemplate">
     <div>
          <div style="float:left;"> ID : </div> <div>${UId} </div>
          <div style="float:left;"> Name : </div> <div>${Name} </div>
          <div style="float:left;"> Address : </div> <div>${Address} </div> <br />
     </div>
 </script>

But, why have I put it in script tag? Because we don't want to render it. We will be using this as a template for displaying the data. Also see, I have made the type as text/html.

Here, in the template, ${UId}, ${Name} and ${Address} are replaced by the actual values from the data provided. The name of the properties in the provided class is the same.

At the server side, I made a WebMethod that will be called from the client to fetch all the person data.

My Person class is as:

C#
public class Person
{
    public int UId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
} 

My WebMethod is as:

C#
[WebMethod()]
public static string GetPersons()
{
    List<person> persons = new List<person>()
    {
        new Person { UId = 1, Name = "Brij", Address = "Noida"},
        new Person { UId = 2, Name = "Rahul", Address = "New Delhi" },
        new Person { UId = 3, Name = "John0", Address = "Chris"}
    };

    JavaScriptSerializer ser = new JavaScriptSerializer();
    return ser.Serialize(persons);
} 

I created the static data in the code, one can fetch from where s/he wants, either some database or some file or some other datasource.

Here I have used the namespace System.Web.Script.Serialization for JavaScript serialization.

I have made an Ajax call at document.ready to get all the persons data, and displayed the data on UI.

JavaScript
//It gets called as soon as DOM gets loaded 

 $(document).ready(function() {
           PopulatePersons();
       });

 //Creating the ajax call, and if succeeded then display the result on UI
 function PopulatePersons() {
     $.ajax({
         type: "POST",
         url: "Default.aspx/GetPersons",
         contentType: "application/json; charset=utf-8",
         data: "{}",
         dataType: "json",
         success: AjaxSucceeded,
         error: AjaxFailed
     }); 

        }
        function AjaxSucceeded(result) {
            Display(result);
        }
        function AjaxFailed(result) {
            alert('no success');
        }

After fetching the data, from the server, we are rendering the data using jquery templating feature:

JavaScript
function Display(result) {

            var persons = eval(result.d);
            personCount = persons.length;
                $("#personTemplate").tmpl(persons).appendTo($("#divPerson"));
        }

Here, what I am doing is that I am parsing the data that is returned by webservice. After that, I am passing it to the tmpl function. This line of code...

JavaScript
$("#personTemplate").tmpl(persons).appendTo($("#divPerson"));

...means use the template personTemplate for rendering the persons data and add it to the container div divPerson.

Adding/Updating Data

For adding more person on UI, I have added an HTML button on my page, to add a person. As:

XML
<input id="Button1" type="button" value="AddMorePerson" 
       onclick="AddPerson();"/>

OnClientclick of Add button, I am fetching the data from server using Ajax call.

JavaScript
function AddPerson() {

            var inputs = new Object();
            inputs.count = personCount;

            $.ajax({
                type: "POST",
                url: "Template.aspx/AddPerson",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(inputs),
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });         
        } 

After fetching the data, display it with the help of client templating as:

JavaScript
function DisplayChildren(result) {

           var persons = eval(result.d);
           personCount = persons.length;
               $("#personTemplate").tmpl(persons).appendTo($("#divPerson"));
       }

It just appends the person detail in the existing div as above.

Note: One should keep in sync the name of the properties of the class and used in template one.

Nested Templates

Nested Templates also work the same as above, but here we'll be using one template in the other. This type of requirement is very common, when we need to show the details of any item one to many or many to many mapping.

So here, I have discussed it with a sample example. Here, I have an employee class which has a list of addresses. It means an employeee can belong to multiple addresses. My employee and address class are like:

C#
public class Address
{
    public string Street { get; set; }
    public String AddressLine1 { get; set; }
    public String AddressLine2 { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
}

and Employee class:

C#
public class Employee
{
    public int EmployeeId { get; set; }
    public String Name { get; set; }
    public int Age { get; set; }
    public List Addresses { get; set; }


<address>}
</address>

Now the webmethod that is returning the data:

C#
[WebMethod()]
 public static string GetEmployees()
 {
    List<employee> persons = new List<employee>()
    {
         new Employee { EmployeeId = 1000, Age=34, Name ="Rahul", 
             Addresses = new List()},
         new Employee { EmployeeId = 1001, Age=29, Name ="Atul", 
             Addresses = new List()},
         new Employee { EmployeeId = 1002, Age=32, Name ="Rohan", 
             Addresses = new List()}
     };
    persons[0].Addresses.Add(new Address() { 
    Street = "Street 5", AddressLine1 = "New Bay Area",
    AddressLine2 = "Near Roma Hospital", City = "Kolkata", Zip = "221001" });

    persons[0].Addresses.Add(new Address() { 
    Street = "Bahadur marg", AddressLine1 = "Kailash Colony", 
    AddressLine2 = "Near Public School", City = "Lucknow", Zip = "226001" });
            
    persons[0].Addresses.Add(new Address() { 
    Street = "Ali Crossing", AddressLine1 = "Republic Colony", 
    AddressLine2 = "Silk Garden", City = "Ahamedabad", Zip = "221021" });

    persons[1].Addresses.Add(new Address() { 
    Street = "Street No 2", AddressLine1 = "Pocket Gama", 
    AddressLine2 = "Near Appollo Hospital", City = "G Noida", Zip = "201301" });
        
    persons[1].Addresses.Add(new Address() { 
    Street = "1634", AddressLine1 = "Sector 15", 
    AddressLine2 = "Near Nirulas", City = "Noida", Zip = "201301" });

    persons[2].Addresses.Add(new Address() { 
    Street = "Street 10", AddressLine1 = "Sector 18", 
    AddressLine2 = "Near Mosaic", City = "Noida", Zip = "201301" });

    persons[2].Addresses.Add(new Address() { 
    Street = "Gol Marg", AddressLine1 = "New Era Colony", 
    AddressLine2 = "Pitambaram", City = "Alllahabad", Zip = "221001" });
        
    JavaScriptSerializer ser = new JavaScriptSerializer();
    return ser.Serialize(persons);
    }
}

Now as above at the client side, this data is displayed using templating feature.

Now at client side, my client side templates would be:

Parent Template

XML
<script type="text/html" id="empTemplate">
    <div>
            <div style="float:left;font-weight:bold;"> ID : </div> 
            <div>${EmployeeId} </div>
            <div style="float:left;font-weight:bold;"> Name : </div> 
            <div>${Name} </div>
            <div style="float:left;font-weight:bold;"> Age : </div> 
            <div>${Age} </div>
            <div style="font-weight:bold;">Addresses:</div>
            <div style="margin-left:10px;">{{tmpl($data) "#AddressTemplate"}}</div>
    </div>
 </script>

Child Template

XML
<script id="AddressTemplate" type="text/html">
      {{each Addresses}}
           <div style="float:left;font-weight:bold;"> Street : </div> 
       <div>${Street} </div>
           <div style="float:left;font-weight:bold;"> AddressLine1 : </div> 
     <div>${AddressLine1} </div>
           <div style="float:left;font-weight:bold;"> AddressLine2 : </div> 
     <div>${AddressLine2} </div>
           <div style="float:left;font-weight:bold;"> City : </div> 
     <div>${City} </div>
           <div style="float:left;font-weight:bold;"> Zip : </div> 
    <div>${Zip} </div><br />
      {{/each}}
 </script>

As here you can see in the child template, I have put the template in the tags {{each Addresses}}{{/each}}. It just renders the inside template for every address. It works like foreach.

Now inside the parent template, the line code...

C#
{{tmpl($data) "#AddressTemplate"}}

... indicates it gets the data, i.e., here list of Addresses and applies the templating on the template AddressTemplate.

Please find the entire code in the attached sample.

Now let's run the application:

Nested Templates

Figure: Nested Templates in Action

Microsoft Announcements

Around a month ago, Microsoft announced three plugins as the new official plugins for jQuery:

  • Templating
  • Datalinking
  • Globalisation

New Official jQuery Plugins Provide Templating, Data Linking and Globalization

In the upcoming version of jQuery (jQuery 1.5) , we would not require to add a plugin for Templating fetaure. This will be part of jQuery 1.5.

In this article, I discussed Templating and in my upcoming articles, I will be talking about Datalinking and Globalization.

Conclusion

As I already discussed in the Introduction section, that jQuery templating provides us a very rich feature to generate the UI without writing much code and in an efficient manner. So one should use templating feature wherever possible. This feature may be very good, where we display a lot of data and also it may get updated. I used it in my application, in almost every page and found it more efficient than server side code.

Feedback and Suggestions

Hope you like this article. Please give your valuable feedback which will be very helpful for me to write better content next time.

License

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


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions

 
GeneralMy vote of 5 Pin
Rakesh Kohale14-Apr-16 0:48
professionalRakesh Kohale14-Apr-16 0:48 
QuestionGreat Article! Pin
Rakesh Kohale14-Apr-16 0:46
professionalRakesh Kohale14-Apr-16 0:46 
QuestionGood Explanation Pin
Alireza_136215-Mar-16 3:50
Alireza_136215-Mar-16 3:50 
GeneralMy vote of 2 Pin
Member 987791011-Sep-13 21:39
Member 987791011-Sep-13 21:39 
QuestionMy vote of 5 Pin
Jaime García30-Aug-13 2:11
Jaime García30-Aug-13 2:11 
GeneralMy vote of 5 Pin
Adebayo James12-Jul-13 0:32
Adebayo James12-Jul-13 0:32 
GeneralMy vote of 5 Pin
  Forogar  22-Feb-13 3:47
professional  Forogar  22-Feb-13 3:47 
GeneralMy vote of 5 Pin
Savalia Manoj M8-Nov-12 16:33
Savalia Manoj M8-Nov-12 16:33 
GeneralMy vote of 5 Pin
Kalpesh Desai25-Mar-12 9:36
Kalpesh Desai25-Mar-12 9:36 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey2-Feb-12 22:55
professionalManoj Kumar Choubey2-Feb-12 22:55 
QuestionMy Five... Pin
Paul Conrad7-Aug-11 8:28
professionalPaul Conrad7-Aug-11 8:28 
AnswerRe: My Five... Pin
Brij7-Aug-11 8:30
mentorBrij7-Aug-11 8:30 
GeneralMy vote of 5 Pin
Member 34159525-Apr-11 19:26
Member 34159525-Apr-11 19:26 
GeneralRe: My vote of 5 Pin
Brij25-Apr-11 19:47
mentorBrij25-Apr-11 19:47 
GeneralMy vote of 3 Pin
masterJalchr11-Jan-11 3:45
masterJalchr11-Jan-11 3:45 
GeneralRe: My vote of 3 Pin
Brij11-Jan-11 6:29
mentorBrij11-Jan-11 6:29 
GeneralRe: My vote of 3 Pin
thatraja26-Feb-11 17:56
professionalthatraja26-Feb-11 17:56 
GeneralRe: My vote of 3 Pin
masterJalchr27-Feb-11 23:06
masterJalchr27-Feb-11 23:06 
GeneralRe: My vote of 3 Pin
thatraja27-Feb-11 23:09
professionalthatraja27-Feb-11 23:09 
GeneralMy vote of 4 Pin
Schmuli10-Jan-11 23:53
Schmuli10-Jan-11 23:53 
GeneralRe: My vote of 4 Pin
Brij11-Jan-11 6:31
mentorBrij11-Jan-11 6:31 
GeneralRe: My vote of 4 Pin
Adam Tibi26-Jan-11 23:16
professionalAdam Tibi26-Jan-11 23:16 
GeneralRe: My vote of 4 Pin
Schmuli2-Feb-11 4:52
Schmuli2-Feb-11 4:52 
QuestionPermissions Client Side ? Pin
Member 382109310-Jan-11 5:02
Member 382109310-Jan-11 5:02 
AnswerRe: Permissions Client Side ? Pin
Brij11-Jan-11 19:44
mentorBrij11-Jan-11 19:44 

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.