Home > ASP.NET MVC, dotnet 4, JQuery, VS 2010 > JQuery Template

JQuery Template

One of the reasons I started blogging was to document my project and learning experiences while working on complex problems. Right from the beginning of my career I was good in writing quick prototypes and small end-to-end proof of concepts, but what I was really not good at was the ability to remember it after sometime. So that way my blog is becoming my software repository and I am glad that it helping other guys who are about to use a particular technology or design principle.

In today’s post I am going to talk about JQuery Template although I did mention briefly about it in my previous post a 8 months ago. But this time I am going to show a full end to end solution and some tips.

The powerful thing about JQuery template is that the template runs in the browser (i.e. on client side) and hence you are taking the client CPU in order to process the template, it’s also better than using string concatenation server side and building HTML string.

So I am going to show a simple list of contact i.e Full name,Age,Phone and some sort of description and our contact class looks like this.

Contact.cs

public class Contact
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Phone { get; set; }
    public string Description { get; set; }

    public Contact(string name,int age,string phone,string description)
    {
        Name = name;
        Age = age;
        Phone = phone;
        Description = description;
    }
}

and the controller

ContactController.cs

public class ContactController : Controller
{
    public JsonResult GetContacts()
    {
        List<Contact> contacts = new List<Contact>()
        {
            new Contact("Joe Blogg",29,"02-6290-0011","A good fellow"),
            new Contact("James Weathers",39,"02-6290-0012","An intelligent fellow"),
            new Contact("John Smith",49,"02-6290-0013","A very wise fellow")
        }; // Just for the demo

        return Json(contacts, JsonRequestBehavior.AllowGet);
    }
}

The reason for returning a JSONResultSet is to show you guys how we can use JQuery to invoke the controller action. Lets see how the view looks like.

Index.aspx

<%@ Page Title="" Language="C#" 
         MasterPageFile="~/Views/Shared/Site.Master" 
         Inherits="System.Web.Mvc.ViewPage<JQueryTemplate.Models.Contact>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Contact
</asp:Content
>
<
asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Contact</h2>
    <script type="text/javascript">

        var templateName = "contactTemplate";
        var resultList = "#contactList";

        $(document).ready(function () {
            $("#jq-getData").click(function () {
                showContacts();
            });
        });

        function showContacts() {
            $.getJSON("/Contact/GetContacts", function (data) {
                var markup = getMarkup();
                clearResultList();
                loadTemplate(templateName, markup);
                applyTemplate(data);
            });
        };

        function getMarkup() {
            var markup = "<tr><td colspan=’2′ title=’${Description}’>${Name}</td><td>Age: ${Age}</td><td>Phone: ${Phone}</td></tr>";
            return markup;
        };

        function clearResultList() {
            $(resultList).empty();
        };

        function loadTemplate(templateName, markup) {
            $.template(templateName, markup);
        };

        function applyTemplate(data) {
            $.tmpl(templateName, data).appendTo(resultList);
        };

    </script>

    <input type="button" id="jq-getData" value="Click" />
    <table><tbody id="contactList"></tbody></table
>
</
asp:Content
>

Okay that looks bit lengthy code and I will try to break it down, I will start with the main function showContacts as it is main method which orchestrate other methods.

1. Get Json data for contacts by invoking the GetContacts action on the controller.

2. Get the markup (html template).

3. Clear the Dom element which will hold the output before any processing.

4. Load the template with the template name and assign the markup to it.

5. Apply the template.

As far as writing the template is concern it’s pure html tags and mark each place holders with the “${attribute}” pattern. The important thing is that the attributes in the template placeholder has to match the property of attribute of your JSON object.Lets run the application and see how it renders on the browser.

Result output

Nothing special as you can see the JSON object has the same attribute as it was in the template markup and the template engine was able to map it and process the html. Lets take a look into the caching headers send by the web server when we requested this JSON object.

Result output

As you can see “Last modified” and “Last fetched” are showing the current time but the “Expiry” header is showing a back date of “1970”, this means that every time the page is refreshed or loaded it will request the JSON over and over again and it can impact on your website performance and scalability. Lets fix it by providing some caching into this request by adding and Output Cache directive to the GetContacts action.

[OutputCache(Duration=60,VaryByParam="")]
public JsonResult GetContacts()
{
    List<Contact> contacts = new List<Contact>()
    {
        new Contact("Joe Blogg",29,"02-6290-0011","A good fellow"),
        new Contact("James Weathers",39,"02-6290-0012","An intelligent fellow"),
        new Contact("John Smith",49,"02-6290-0013","A very wise fellow")
    };

    return Json(contacts, JsonRequestBehavior.AllowGet);
}

After this build the solution and request the page again and you will see the expiry headers are added to the response and now the page will be cached on the browser for a minute.

Result output

That’s it for today and I hope you guys will find this end-to-end JQuery Template solution useful for your projects.BTW the Jquery template is available from Microsoft CDN site at http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js.

Advertisements
  1. August 6, 2012 at 11:03 pm

    Hey! I could have sworn I’ve been to this website before but after browsing through some of the post I realized it’s new to me.
    Anyhow, I’m definitely delighted I found it and I’ll be bookmarking
    and checking back frequently!

    • August 10, 2012 at 4:18 pm

      Hi,
      Thanks for your kind and I really appreciate it. Hope I continue to write better post.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: