In my three previous blogs, I’ve shown how to use Templates in your ASPX website. Introduction to jQuery TemplatesjQuery Templates - tmpl(), template() and tmplItem()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="author"> ${au_lname} ${au_fname} <div id="address">${address}, ${city}</div> <div id="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="author"> ${au_lname} ${au_fname} <div id="address">${address}, ${city}</div> <div id="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