ASP.NET MVC with jTemplates – Part I

One of my goals in web development is to continue to look to use json to transmit data vs. using partial views.  Obviously by transmitting json data, the payload is going to be much more efficient.

I’m going to break this out into two parts :

Part I is going to cover the basics to using jTemplate with jQuery within an asp.net mvc environment.

Part II is going to take this concept and apply it to a nice looking jQuery plugin ‘grid control’ called  DataTables

Let’s look at what the final result will be:

image

Let’s address the server side pieces first:

I’m going to create a new Model class ‘Person’:

public class Person
    {
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
    }

Using the default asp.net mvc created project type, I’ll just a hook into the the Home controller to display the table in the index page.  To do this, I’ll need to add another action with some sample data that will be called from the page via ajax:

 

 [HttpPost]
 public JsonResult GetData()
 {
      IList<Person> people = new List<Person>
        {
          new Person {ID = "1", FirstName = "Anne", Email = "anne@domain.com"},
          new Person {ID = "2", FirstName = "Amelie", Email = "amelie@domain.com"},
          new Person {ID = "3", FirstName = "Polly", Email = "polly@domain.com"},
          new Person {ID = "4", FirstName = "Alice", Email = "alice@domain.com"},
          new Person {ID = "5", FirstName = "Martha", Email = "martha@domain.com"}
        };
      return Json(people);
}

The ‘return Json(people)’ will return the list in json format – which you can see in the above Firebug screenshot ‘response’. 

So that is basically it for the server side.

The first step in the views is to add the references to the javascript files.  Since I’m using the site.master I’ll add it there, so that it’s available to other views as well:

image 

(For production, you will want to use the compressed/min files instead)

I also add a new ContentPlaceHolder in the head of the site.master:

<asp:ContentPlaceHolder ID="HeadContent" runat="server" />

This way on the views, I can put any scripts in the head tags as well.

In the Index.aspx page we can finish this functionality:

1. add the scripts to the head of the view:

<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {
        $.ajax({
                type:"POST",
                url: "<%= Url.Action("GetData") %>",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                    $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                    $("#jTemplateDemo").processTemplate(data);
                }
            });
        });
    </script>
</asp:Content>

To review this (we could use a $.getJSON as well) – on the page ready function I’m going to make an ajax call back to the ‘GetData’ action.  This is defined in the ‘url:’ parameter.

In this case there are no parameters being passed so the data is left blank (this is best practice to include “{}” when blank).  It is possible to use a REST url as well with parameters.

We define out contentType (using $.getJSON) would do this automatically.

Lastly, we provide an ‘onSuccess’ function – the ‘data’ will contain the returning Json from our action call.  The next two calls use the jTemplate API to merge the Json data to the templated html, as shown below.

2. add the template to the view:

<script type="text/html" id="templateHolder">
    <table border="1">
    <tr>
        <th>
            First Name
        </th>
        <th>
            Email
        </th>
    </tr>
    {#foreach $T as record}
        <tr>
            <td>
                {$T.record.FirstName}
            </td>
            <td>
                {$T.record.Email}
            </td>
        </tr>
    {#/for}
</table>
</script>

<div id="jTemplateDemo">
</div>

 

One thing to keep in mind is to put this html in the script tag.  Alternatively you could load this template from another file as well.

With this approach we have created a very lightweight approach to passing data from the server to the client – the binding to the template occurs on the client.  If we used partial views, the binding process would occur on the server and transmit the payload with the html, increasing it’s size.  The lightweight json approach is critical especially in our ajax calls

Next post we’ll take this table and convert it into a ‘DataTable’.

I have included this code for your review – download here

Advertisements

7 thoughts on “ASP.NET MVC with jTemplates – Part I

  1. Thanks for article.

    This works, but because you put the template in script, you can’t do things like register an event handler for row selection (for example). The event doesn’t get bubbled up to script.

  2. I’ve been converting my server-side templates in ASP.NET to using this method, but i realised recently that this may not be very smart from a SEO perspective. If all my tables are rendered on the client, there is nothing for Google to index..

    Do you have a solution to this problem? For instance when providing deep links that run a search or similar to fill a table right away, and then afterwards provide a dynamic way to update it. Should i pre-render some of the data in some way for the googlebot, or is there a smarter way?

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