Practical ASP.NET

Displaying and Filtering Data with jQuery Templates

Building on the new jQuery extensions for displaying multiple rows, Peter builds a page that retrieves data from a Web Service based on the user's input -- and filters the data in the client as well.

In my last column (Setting Up for jQuery Templates), I set up a simple AJAX-enabled page that uses client-side code to retrieve the Order objects for a customer from a WCF Web when the user selected a customer from a dropdownlist on the page. In this column, I'm going to display those objects in a table using the new template plug-in for jQuery (and support filtering those orders by date).

The first step in this process is to create a template, which defines how each Order object will be displayed. A template is put into the page, inside a script block with a type of text/x-jquery-tmpl (putting the template inside the script block prevents the browser from rendering it before I'm ready). A copy of the template will be repeated once for each object returned from the Web Service. Properties from the object are inserted into the template where you insert their names, enclosed inside $().

The following template creates a row from a table with two cells: one cell displays my DTO's OrderId property and the other cell displaying the RequiredDate property:

<script id="OrdersGridTemplate" type="text/x-jquery-tmpl">
   <tr>
     <td>${OrderId}</td>
     <td>${RequiredDate}</td>
   </tr>
</script>

I also need to establish someplace in my page to insert the resulting rendered template. For this example, I'm going to set up a table with headings in the thead section and a tbody where the rendered template will be displayed. I assign an id to the tbody section so I can reference it from my JavaScript code:

<table>
  <thead>
    <tr>
      <td>Order Id</td>
      <td>Required Date</td>
    </tr>
  </thead>
  <tbody id="OrdersGridDisplay"></tbody>
</table>

To render the template, I use a jQuery selector to retrieve the script block containing the template and then use the new tmpl plugin to render the template. The data to be incorporated into the template is passed as a parameter to the tmpl plug in. The resulting rendered template can be added to the page using a variety of plugins -- initially, I'll use the appendto plugin.

This example retrieves the template in the OrdergridTemplate scriptblock, renders it with the tmpl plugin, passing the collection of objects returned from the Web service (I store the orders in a global variable so I can use it throughout the page). The output is appended to the element with an id of OrderGridDisplay:

$("#OrdersGridTemplate").tmpl(ords).appendTo("#OrdersGridDisplay");

The problem with this solution is that, if the user selects a new customer, the new orders will be added to the previous list of orders. To allow the user to change from one customer to another and replace the previous customer's order, I'll use the get plugin to retrieve the HTML from the generated template. I'll then insert that HTML into the OrdersGridDisplay, replacing any existing list, using the html plugin:

var ords;
function GotOrders(orders) {
    ords = orders;
    var gridHtml = $("#OrdersGridTemplate").tmpl(ords).get();
    $("#OrdersGridDisplay").html(gridHtml);
}

However, if I'm allowing my users to select new customers, re-rendering the template each time is a waste of time. I can "pre-compile" the template and cache it under a name by using the template plugin. This example retrieves the template and caches it under the name OrdersGridTemplateCached:

$("#OrdersGridTemplate").template("OrdersGridTemplateCached");

Once the template is a cache, I can pass the name of the cached template and the objects to render as parameters to the tmpl plugin. However, I only want to cache the template if the user actually needs it and I only want to cache the template once. A variation on the template plugin lets me store the cached template in a variable. By checking the variable, I can determine if I've cached the template and, if I haven't, cache it. That's what this code does so that the template is cached only the first time it is rendered:

var OrdersGridTemplateHold;
function GotOrders(ords) {
  if (OrdersGridTemplateHold == null) {
      OrdersGridTemplateHold = $("#OrdersGridTemplate").template();
  }
  var gridHtml = $.tmpl(OrdersGridTemplateHold, ords).get();
  $("#OrdersGridDisplay").html(gridHtml);
}

If you want to merge property values with the text in a tag, you can use the {{= }} syntax. For instance, I want to display the order's RequiredDate in a textbox to allow the user to update it. To generate that textbox in the template, setting the value of the textbox to the value of the RequiredDate property, I used this code:

<td><input type="text" id="RequiredDate" 
    value="{{= RequiredDate}}"/></td>

I can also filter rows by using the {{if}}{{/if}} structure to decide which parts of the template will be rendered. In the {{if}} construct you can call a function, passing properties from the object being rendered. If the function returns true, the portion of the template enclosed in the {{if}} structure is rendered; if the function returns false, that portion of the template is skipped. This example suppresses a row based on the value returned by the function CheckAfterDate which is passed the RequiredDate property of the object being rendered:

{{if CheckAfterDate(RequiredDate)}}
   <td><input type="text" id="RDate{{= OrderId}}" 
    value="{{= RequiredDate}}"/></td>
   <td>${RequiredDate}</td>
{{/if}}            

The corresponding CheckAfterDate function might look like the following. This example retrieves a year from a control on the page and uses that to test the value of the date passed to it:

function CheckAfterDate(requiredDate) {
    var yr = $("#lstYears").val();
    if (new Date(requiredDate).getYear() >= yr) {
        return true;
    }
    else {
        return false;
    }    
}

At this point, I've got a page that retrieves data based on the user's input and filters the data (in the client), again based on the user's input. The next step is to support updating rows, which is my next column (where I'll be using the new databinding extension to jQuery).

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube