Basics steps:
- Embed some hidden DOM inside a <script type=”text/html”> tags inside your page document.
- Make a JSON request or build an object which will be used as a data source.
- Using jQuery and this templating extension, you can inject the data from step 2 into the template.
- Insert this data injected template somewhere in your page.
So those are the basic steps, lets see some code. I’m going to be using a html table as an example because that lends itself to the obvious add a row concept.
1. The html page with embedded template html snippet
<html>
<table id="OrderTable" width="100%" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th />
<th>Quantity</th>
<th>Name</th>
<th>Price</th>
<th />
</tr>
</thead>
<tbody>
<tr>
<td><a href="”/Order/abc1234/Edit/1”">Edit</a></td>
<td> 1 </td>
<td>Some Product</td>
<td>5.50</td>
<td />
</tr>
</tbody>
</table>
<script id="RowTemplate" type="text/html"> 1:
<tr id="${Tag}_Order">
<td><a href="<%= Url.Action("Edit")%>/${Tag}">Edit</a></td>
<td>${Quantity}</td>
<td>${Name}</td>
<td>${Price} </td>
<td><a id="${Tag}_Delete" href="<%= Url.Action("Delete")%>/${Tag}">Delete</a></td>
</tr>
<div id="AddProduct">
<% using (Html.BeginForm("AddProduct", "Orders", FormMethod.Post))
{ %>
<div><input type="submit" value="Add Product" /></div>
<label>Product:</label><%= Html.DropDownList("products")%>
<label>Quantity:</label><input id="Quantity" name="Quantity" type="text" />
<% } %>
</div>
<script type="text/javascript">
$("#AddProduct form").submit(addProduct); // hijax product add form submission using jQuery
</html>
2. Make a JSON request in order to get back some data in the form
3 & 4. Using the jQuery template extension inject the data and append to DOM
The jQuery template library will use the html snippet from the <script> block to create a template object. Then the JSON that was returned will be applied to the template. The key to remember here is that the JSON’s object properties, such as Quantity or Price, match to names in the template like ${Quantity} or ${Price}, respectively.
function addProduct_sucess(response)
{
// using template libarary, create template object using html snippet
var t = $.template($("#RowTemplate").html());
// response = { Tag:3, Quantity:2, Name:"Snuggy", Price:19.95 }, notice that property names match to template ${...} names.
var row = $(t.apply(response));
// appned this DOM row object to our table
$("#OrderTable tbody").append(row);
}