jQuery Templates with ASP.NET MVC

In my three previous blogs, I’ve shown how to use Templates in your ASPX website.

  1. Introduction to jQuery Templates
  2. jQuery Templates - tmpl(), template() and tmplItem()
  3. jQuery Templates - {Supported Tags}

Now, I will show one real-world example which you may use it in your daily work of developing applications with ASP.NET MVC and jQuery.

In the following example I will use Pubs database so that I will retrieve values from the authors table. To access the data, I’m using Entity Framework.

Let’s pass throughout each step of the scenario:

1. Create new ASP.NET MVC Web application

2. Add new View inside Home folder but do not select a master page, and add Controller for your View

3. BODY code in the HTML

<body>
    <div>
        <h1>Pubs Authors</h1>
        <div id="authorsList"></div>
    </div>
</body>

As you can see  in the body we have only one H1 tag and a div with id authorsList where we will append the data from database.

 

4. Now, I’ve created Pubs model which is connected to the Pub database and I’ve selected only the authors table in my EDMX model. You can use your own database.

5. Next, lets create one method of JsonResult type which will get the data from database and serialize it into JSON string.

public JsonResult GetAuthors()
{
    pubsEntities pubs = new pubsEntities();
    var authors = pubs.authors.ToList();
    return Json(authors, JsonRequestBehavior.AllowGet);
}

So, I’m creating object instance of pubsEntities and get all authors in authors list. Then returning the authors list by serializing it to JSON using Json method. The JsonRequestBehaviour.AllowGet parameter is used to make the GET requests from the client become allowed. By default in ASP.NET MVC 2 the GET is not allowed because of security issue with JSON hijacking.

 

6. Next, lets create jQuery AJAX function which will call the GetAuthors method. We will use $.getJSON jQuery method.

<script language="javascript" type="text/javascript">
    $(function () {
        $.getJSON("GetAuthors", "", function (data) {
            $("#authorsTemplate").tmpl(data).appendTo("#authorsList");
        });
    });
</script>

 

Once the web page is downloaded, the method will be called. The first parameter of $.getJSON() is url string in our case the method name. The second parameter (which in the example is empty string) is the key value pairs that will be send to the server, and the third function is the callback function or the result which is going to be returned from the server.

Inside the callback function we have code that renders data with template which has id #authorsTemplate and appends it to element which has #authorsList ID.

 

7. The jQuery Template

<script id="authorsTemplate" type="text/html">
    <div id="${au_id}" class="author">
        ${au_lname} ${au_fname}
        <div class="address">${address}, ${city}</div>
        <div class="contractType">            
        {{if contract}}
            <font color="green">Has contract with the publishing house</font>
        {{else}}
            <font color="red">Without contract</font>
        {{/if}}
        <br />
        <em> ${printMessage(state)} </em>
        <br />            
        </div>
    </div>
</script>

As you can see, I have tags containing fields (au_lname, au_fname… etc.) that corresponds to the table in the EDMX model which is the same as in the database.

One more thing to note here is that I have printMessage(state) function which is called inside ${ expression/function/field } tag.

The printMessage function

<script language="javascript" type="text/javascript">
    function printMessage(s) {
        if (s=="CA") return "The author is from California";
        else return "The author is not from California";
    }
</script>

So, if state is “CA” print “The author is from California” else “The author is not from California”

 

HERE IS THE COMPLETE ASPX CODE

<!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>Database Example :: jQuery Templates</title>
    <style type="text/css">
        body  
        {
            font-family:Verdana,Arial,Courier New, Sans-Serif;
            color:Black;
            padding:2px, 2px, 2px, 2px;
            background-color:#FF9640;
        }
        .author
        {
            display:block;
            float:left;
            text-decoration:none;
            border:1px solid black;
            background-color:White;
            padding:20px 20px 20px 20px;
            margin-top:2px;
            margin-right:2px;
            font-family:Verdana;
            font-size:12px;
            width:200px;
            height:70px;}
        .address  
        {
            font-style:italic;
            color:Blue;
            font-size:12px;
            font-family:Verdana;
        }
        .author_hover {background-color:Yellow;}
    </style>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">
        function printMessage(s) {
            if (s=="CA") return "The author is from California";
            else return "The author is not from California";
        }
    </script>

    <script id="authorsTemplate" type="text/html">
        <div id="${au_id}" class="author">
            ${au_lname} ${au_fname}
            <div class="address">${address}, ${city}</div>
            <div class="contractType">            
            {{if contract}}
                <font color="green">Has contract with the publishing house</font>
            {{else}}
                <font color="red">Without contract</font>
            {{/if}}
            <br />
            <em> ${printMessage(state)} </em>
            <br />            
            </div>
        </div>
    </script>
    <script language="javascript" type="text/javascript">
        $(function () {
            $.getJSON("GetAuthors", "", function (data) {
                $("#authorsTemplate").tmpl(data).appendTo("#authorsList");
            });
        });
    </script>
</head>
    <body>
    <div id="title">Pubs Authors</div>
    <div id="authorsList"></div>
</body>
</html>

So, in the complete example you also have the CSS style I’m using to stylize the output of my page.

Here is print screen of the end result displayed on the web page:

You can download the complete source code including examples shown in my previous blog posts about jQuery templates and PPT presentation from my last session I had in the local .NET UG meeting in the following DOWNLOAD LINK.

Do let me know your feedback.

Regards,
Hajan

NEXT - jQuery Templates - XHTML Validation

Published Wednesday, December 15, 2010 8:45 PM by hajan

Comments

# re: jQuery Templates with ASP.NET MVC

Wednesday, December 15, 2010 8:00 PM by Ben

Great Post!  This is really helpful.  

We are in the process of re-writing a large CMS to use MVC and was looking for a good example of using jQuery/Ajax to auto complete forms.  I can't wait to get back to the office and try to port this example over.

Thanks

# re: jQuery Templates with ASP.NET MVC

Monday, December 20, 2010 9:37 PM by lovedota21

Thanks your article is Great !

# re: jQuery Templates with ASP.NET MVC

Saturday, January 1, 2011 12:02 PM by Niral

Great Post. Really helped me a lot.

# re: jQuery Templates with ASP.NET MVC

Sunday, January 2, 2011 9:40 AM by Andrea Bioli

This technique is really interesting, but I'm wondering what is the real difference when compared to creating the HTML server side: we get asynchronicity, but apart from this we have also to master just another technique, beware of pitfalls, etc. etc.... Is it really advantageous? If yes, why?

Thanks in advance

Andrea

# re: jQuery Templates with ASP.NET MVC

Tuesday, January 4, 2011 1:13 AM by Saurabh

Awesome.....m luvin it :-)

# re: jQuery Templates with ASP.NET MVC

Tuesday, January 4, 2011 5:18 PM by hajan

@Andrea, if you want to know the real advantages, please read the 'Introduction to jQuery Templates' post on the following link: weblogs.asp.net/.../jquery-templates-in-asp-net-introduction.aspx

Thanks...

# re: jQuery Templates with ASP.NET MVC

Tuesday, January 4, 2011 5:18 PM by hajan

@Saurabh, thank you for your comment :)

# re: jQuery Templates with ASP.NET MVC

Wednesday, January 12, 2011 8:53 PM by David Clarke

I'm curious about your use of the "id" attribute in the template - shouldn't this be the "class" attribute? If you have multiple rows then you would have multiple divs on the same page with the same id or am I missing something?

# re: jQuery Templates with ASP.NET MVC

Thursday, January 13, 2011 4:05 PM by hajan

@David, thank you for the comment.

You are correct and in this way the best would be to use class (.) instead of id (#). Mainly, this doesn't affect the example in the post, however for additional operations class would be more suitable.

# re: jQuery Templates with ASP.NET MVC

Tuesday, January 3, 2012 11:18 PM by Sanath

I really appreciate to the author for posting such a great post on JQuery templates.As jQuery is important in software industries and for Engineering college students.

# re: jQuery Templates with ASP.NET MVC

Saturday, January 7, 2012 7:18 PM by hajan

Thanks Sanath.

# re: jQuery Templates with ASP.NET MVC

Monday, March 26, 2012 6:40 PM by Madeline

And how does that mean? I do not understand anything.

# re: jQuery Templates with ASP.NET MVC

Saturday, November 24, 2012 2:31 PM by Batchelor

Very good article. I absolutely love this site. Keep it up!

Leave a Comment

(required) 
(required) 
(optional)
(required)