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

Introduction

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:

<connectionStrings>
<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"/>
</connectionStrings>

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" %>

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

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:

.sys-template
{
    display:none;
}
th
{
    background-color:Gray;
    border-width:thin;
    border-style:solid;
    border-color:Black;
}
td
{
    border-width:thin;
    border-style:solid;
    border-color:Black;
}

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">
    <title></title>
    <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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellspacing="0">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Age</th>
                    <th>Salary</th>
                    <th>Date Of Joining <br /> (MM/dd/yyyy)</th>
                </tr>               
            </thead>
            <tbody id="EmployeeTemplate" class="sys-template">
                <tr>
                    <td>{{ID}}</td>
                    <td>{{FirstName}}</td>
                    <td>{{LastName}}</td>
                    <td>{{Age}}</td>
                    <td>{{Salary}}</td>
                    <td>{{JoiningDate}}</td>
                </tr>
            </tbody>
        </table>
    </div>
    </form>
</body>
</html>

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
                            },
                            null,
                            null,
                            $get("EmployeeTemplate"));
});

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

[data4.jpg]
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:

[output5.jpg]
Fig 4.0

Conclusion

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!



About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • QA teams don't have time to test everything yet they can't afford to ship buggy code. Learn how Coverity can help organizations shrink their testing cycles and reduce regression risk by focusing their manual and automated testing based on the impact of change.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds