Archive

Posts Tagged ‘JQuery templating’

JQuery Template

March 3, 2011 2 comments

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.

Race Day Commander – Project Setup

I have been very busy with lot of stuff and haven’t been able to focus on the “Race Day commander” project, in fact the day we  put the prototype in codeplex we haven’t had chance to even look at it.

It was good that one of my mates downloaded the project and reported that he had some problems in running the project.I knew what the problem could be and thought I will write a few instruction on how to setup the project.

So here is how you can make at least the project up and running while we work on adding real bits to make it a real-life application.

  1. Download the database file(.bak) and the VS solutions file from here.
  2. Restore it in your SQLExpress database and the name the database as RDC.
  3. Change the connection string in both web.config files i.e. RDC.Admin & RDC.Web project, right now it says BART_PC\SQLExpress and change it to .\SQLExpress.
  4. Run the project and browse to http://localhost:22676/Event/Index/1 as the default routing takes you the home index page and we haven’t fixed it yet.
  5. Open a new instance of your browser and browse to http://localhost:32124/Comments/List.aspx and add comments. This is the dynamic data page which we tried to demonstrate during the demo.
  6. Enter a few sentences in the comment field and enter todays date time in format dd/mm/yy hh:mn:ss so that the comments get added as the latest comment.
  7. Flip back to the main application and you will see the comment appearing automatically.

In upcoming days i will start blogging into “deep dive” kind of stuff, meanwhile any feedback or comment is most welcome.

Race Day Commander
Race Day Commander with comments

JQuery template

June 2, 2010 1 comment

One of the coolest thing in “Race day commander” application is the use of JQuery template. In fact in our work place we have been using the open source “Jtemplate” plugin for quite sometime and it is a a great templating plugin. But at the #webcamp James Senior told us about the microsoft JQuery template and it was fun to use it.

The plugin is available at http://github.com/nje/jquery-tmpl and of course to learn it refer to Scott Gu’s blog.

For us, it was literally changing the ‘#’ character to ‘{‘ and hit refresh :-).

For Example in JTemplate it is:-

<div>
{# CommentText.substr(0,250) }
{#if CommentText.length > 250}<span>… more</span>
{#/if}
</div>

And in JQuery template it would be:-

<div>
{{= CommentText.substr(0,250) }}
{{if CommentText.length > 250}}<span>… more</span>
{{/if}}
</div>

This is really a cool way of making your page interactive and implementing “progressive disclosure” logic by having a template in the page and return tiny json objects and is not limited to ASP.NET MVC, in fact I use it a lot in my webforms which still have UpdatePanels ( Urrggghhh !!! )