Using DataView to Bind Client Side Template in ASP.NET AJAX 4.0

by V.N.S Arun

Learn to fetch data from the database by creating an entity data model and an ADO.NET data service for exposing the data.


In this article I will illustrate a step by step process of performing a client template binding using a DataView in AJAX 4.0. Client template binding is a notable feature in AJAX 4.0 which will allow developers to bind the data to a client side control like an HTMLTable and the data access (ADO.NET data service) will also be called from the client side making sure that the code behind the web site will not be involved in fetching the data or binding it to the control.

In this article for fetching the data from the database I will be creating an entity data model and an ADO.NET data service for exposing the data.

Create demo application

Since the article is about ASP.NET applications, as a first step let us go ahead and create a basic web site. Create a website which is called as Empty Website in the New Website window. If you create a website named ASP.NET website in VS2010 the website will be created with a pre defined website template which will include basic styles, login, register user pages, etc., which is not required for us in this demo.

Adding a Local Database

Add an App_Data ASP.NET folder and add a local database under it. I am adding it as a local database since it doesn't require any dedicated server for working against. Name it EmployeeDatabase and create a table called Employee in the database. Fig 1.0 shows the schema of the Employee table.

Fig 1.0 - Add some sample data to the Employee table, I have the screen shot of my sample data in Fig 1.1

Fig 1.1 Represent the Employee table using ADO.NET Entity Data Model

Add an App_Code ASP.NET folder and add an ADO.NET Entity Data Model for representing the Employee table at the application level.

Name the entity data model as EmployeeDataModel.edmx, define the SQL connection and choose the Employee table from the Employee database. Below is the connection string which will be generated and kept in the web.config file:

<add name="EmployeeDatabaseEntities" connectionString="metadata=res://*/App_Code.EmployeeDataModel.csdl|res://*/App_Code.EmployeeDataModel.ssdl|res://*/App_Code.EmployeeDataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\EmployeeDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"/>

Fig 2.0 shows the .edmx design

Fig 2.0 - Expose the data access using a ADO.NET data service

In order to do a data retrieval from the AJAX libraries on the client side the data access should be exposed through web service, WCF service or an ADO.NET data service. For this demo application I will use ADO.NET data service.

Right click on the website and add ad ADO.NET Data Service and name it EmployeeDataService.svc. Below is the code behind for the data service:

public class EmployeeDataService : DataService<EmployeeDatabaseEntities>
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
        config.SetEntitySetAccessRule("*", EntitySetRights.All);

Note that the inherited generic class DataService is strongly typed with EmployeeDatabaseEntities class which has been created automatically when entity model was created.

Here is the ServiceHost directive on the .svc file

<%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory" Service="EmployeeDataService" %>

Add ASP.NET AJAX 4.0 and JQuery libraries

Download AJAX 4.0 beta libraries from here. The libraries which are required for the client side template binding are listed below:

  1. MicrosoftAjax.js - For normal ajax functionalities
  2. MicrosoftAjaxAdoNet.js - Since we use Sys.Data.AdoNetDataContext object
  3. MicrosoftAjaxTemplates.js - Since we use Sys.UI.DataView for binding data to client templates

Only adding the above JavaScript libraries to the website should be enough. In our demo web site I am adding their debug versions. Add the JQuery library as well to the website since we will be using JQuery for getting the client template and creating AdoNetDataContext and DataView objects.

Create another .js file named ClientBinding.js and leave it empty which we will use to write the JavaScript code to retrieve data and binding it to the client template.

Define a StyleSheet

Add a new .css file and name it as Default.css. Add styles to the .css file since we are going to create an HTML table to which the data is going to be binded. Below is the style sheet content:


Client Side Template Binding

Until now we were setting up the base for the demo application. Now let us create an .aspx file and name it EmployeeUI.aspx and define an HTML table with a header and a few databinding things.

  <html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <link href="Styles/Default.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="scripts/ajax/MicrosoftAjax.debug.js"></script>
    <script type="text/javascript" src="scripts/ajax/MicrosoftAjaxTemplates.debug.js"></script>
    <script type="text/javascript" src="scripts/ajax/MicrosoftAjaxAdoNet.debug.js"></script>
    <script src="Scripts/ClientBinding.js"  type="text/javascript"></script>
    <form id="form1" runat="server">
        <table cellspacing="0">
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Date Of Joining <br /> (MM/dd/yyyy)</th>
            <tbody id="EmployeeTemplate" class="sys-template">

In the above code check the way the header is defined and I am sure that you would ask yourself what the double curly braces around the column names are. Well in AJAX 4.0, binding this is the syntax used to define column binding. You could also use {binding columnName} instead of {{columnName}}.

Also note the tbody of the table is decorated with the class sys-template which is nothing but display:none. This is done in order to hide the static row defined and only show the databound rows.

Now let us open the javascript file ClientBinding.js and start writing the code to perform the data retrieval and template binding. I am making use of the add_init event of the page so this code is run during the page initialization event. Here is the JavaScript code:

Sys.Application.add_init(function () {
        var dataContext = $create(Sys.Data.AdoNetDataContext,
                                serviceUri: "EmployeeDataService.svc"

    var employeeTemplate = $create(Sys.UI.DataView,
                                dataProvider: dataContext,
                                fetchOperation: "Employees",
                                fetchParameters: {$orderby: "ID"},
                                autoFetch: true

Note that I am passing the fetchParameters as $orderby ID so the records displayed on the page would be ordered by the column ID. Now run the application by setting EmployeeUI.aspx as the start page.

Fig 3.0 shows the output on the browser

Fig 3.0 - Formatting data

Everything looks great about this client side template binding except the date field, the time stamp on the date looks ugly. What if I want to format the date which is getting bound? Here is the solution, create a function named formatDate in the ClientBinding.js file to return the formatted date. Below is the function:

function formatDate(dateValue) {
    var month = dateValue.getMonth();
    var year = dateValue.getFullYear();
    var date = dateValue.getDate();

    return month + "/" + date + "/" + year;

In the EmployeeUI.aspx page in the td element for JoiningDate change the databinding script as {binding JoiningDate, convert=formatDate}, this will call the function formatDate and get the formatted date back. So here is the modified .aspx code:

<tbody id="EmployeeTemplate" class="sys-template">                <tr>                    <td>{{ID}}</td>                    <td>{{FirstName}}</td>                    <td>{{LastName}}</td>                    <td>{{Age}}</td>                    <td>{{Salary}}</td>                    <td>{binding JoiningDate, convert=formatDate}</td>                </tr> </tbody>

Fig 4.0 shows the output screen:

Fig 4.0


I have attached the source code for this demo web site. The feature doesn't end here. In my next article I will be demonstrating how to perform a two way binding in the client side templates using AJAX 4.0. Hope you enjoyed!

This article was originally published on Monday May 17th 2010
Mobile Site | Full Site