Thursday, July 5, 2012

Js Library: Client-side template to output data - jQuery Templates


No included in MVC. Can use NuGet tools to get it. Right click on project. Look for jQuery templates.
Add Library Package Reference. Search for jquery template (jquery.tmpl.js)
In Script tag to include: jQuery-tmpl-min.js
Only jquery template plug-in will use the following. Browsers will ignore because fof type
// jQuery template with data which has Name, City and Country property
<script id=”searchTemplate” type=”text/x-jquery-tmpl”>
<tr>
<td>${Name}</td>
<td>${City}, ${Country}</td>
</tr>
</script>
Steps
1. Use a standard form tag. Using jquery instead of using jquery helpers.
<form method=”get”
action=”@Url.Action(“JsonSearch”, “Home”)”
id=”searchForm”>
  <input type=”text” name=”q” data-autocomplete=”@Url.Action(“QuickSearch”, “Home”)”
  <input type=”submit” value=”Search”/>
</form>

public ActionResult JsonSearch(string q)
{
  var restaurants = _db.Restaurants
  .Where( r=> r.Name.Contains(q) || String.IsNullOrEmpty(q))
  .Take(10)
  .Select (r => new
   {
     r.Name, r.Address.City, r.Address.Country
});
return Json(restaurants, JsonRequestBehavior.AllowGet);
}

2. OnReady hookup the Submit event of the Form
$(document).ready(function() {
... // autocomplete
... // date picker
$(“#searchForm”).submit(function() {
$.getJSON($(this).attr(“action”),  // the url to get JSON from
$(this).serialize(),   /// serialize the values posted i.e. q=yellow
function (data) {       // what to do with the response
  var result = $(“#searchTemplate”).tmpl(data);  // use tmpl function to find the template
   $(“#searchResults”).empty().append(result);
}
return false;
}