ASP.NET AJAX 4.0 Preview 5 – Working with Converters and the new CDN

In this blog post I’m going to show you how you can use the new Converter feature during data binding, to make this post more special I have used the new Microsoft AJAX CDN (Content Delivery Network), so I don’t need to have the AJAX 4.0 script on my server. The example code I use in this post, will use the ASP.NET AJAX DataView and also Microsoft ADO.NET Data Services to retrieve data from the server. My fantasy isn’t so special good, but I decided to make a little “rental” application, where I will use ASP.NET AJAX to simply show a list of cars and the current rental status. The status of a rental car will be sent to the client as a string and can be of the following values, Approved, Not Approved and Pending. The little app I’m building for this post, will show the rental status as different colors for the user.

image


Green color will show that the rental of the car is approved, red will indicate not approved and yellow will indicate a pending status. My little database have one simple table, called Rental (lack of fantasy), with three columns, ID, Description and Status. I have used Entity Framework together with ADO.Net Data Source to get the data from the database. Here is the ADO.NET Data Service, I have added a Rental operation to only enable access to the operation to get Rental entities.

public class RentalWebDataService : DataService<RentalModel.RentalEntities>
{
    public static void InitializeService(IDataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("Rental", EntitySetRights.AllRead);
        config.SetServiceOperationAccessRule("Rental", ServiceOperationRights.AllRead);
    }

    [WebGet]
    public IQueryable<RentalModel.Rental> Rental()
    {
        return this.CurrentDataSource.Rental;
    }
}

To use ASP.NET AJAX 4.0 Preview 5, I have not used my local scripts, instead use the new Microsoft AJAX CDN. The Microsoft CDN service provides caching support for AJAX libraries (including jQuery and ASP.NET AJAX) and are composed of “edge cache” servers, they are strategically placed around the world to make sure your application will use the nearest server to get the ASP.NET AJAX scripts, isn’t that cool?! The service is free and both for commercial and non-commercial purpose. To get a JavaScript from the Microsoft CDN, you can simply use the <script> tag to include the script from ”http://ajax.microsoft.com/ajax”. Microsoft CND will use sub folders to versioning the different kind of scripts. The ASP.NET AJAX 4.0 Preview 5.0 script can be found under the /0909/ folder (the name of the folder represents the year and month when the ASP.NET AJAX was released). You can find the JavaScript and URLs here: http://www.asp.net/ajax/cdn/

Note: ScriptManger can automatically request JavaScript files form the Microsoft CDN if the EnableCdn property of the ScriptManager is set to true.


I have used the following code to include the ASP.NET AJAX 4.0 Preview 5.0 script in my demo, to make sure I can use Templates, and ADO.NET DataServices:

<script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjax.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxTemplates.js" type="text/javascript"></script> <script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxAdoNet.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxDataContext.js" type="text/javascript"></script>


To use the ADO.NET Data Service (RentalWebDataSerivce) on the client-side, the ASP.NET AJAX $create shortcut can be used to create a ADO.Net DataContext object, the DataContex is the proxy class to access the ADO.Net Data Service:

var RentalService = {};

RentalService.dataContext = $create(Sys.Data.AdoNetDataContext,
                                         {
                                             serviceUri: "RentalWebDataService.svc",
                                             mergeOption: Sys.Data.MergeOption.appendOnly
                                         });

The following is the template I have used to list the cars:

 <table sys:attach="dataview"
        class="sys-template"
        dataview:dataprovider="{{ RentalService.dataContext }}"
        dataview:fetchoperation="Rental"
        dataview:autofetch="true">

        <tr sys:if="$index==0">
            <td>Booking No</td>
            <td>Description</td>
        </tr>
        
         <tr sys:style-background-color="{binding Status, convert=convertStatusToColor, ColorType=Name}">
             <td>{{ ID }}</td>
             <td>{{ Description }}</td>
         </tr>
</table>


Yes, I know, I use a table instead of a DIV, shame on me..

To create a template the class=”sys-template” must be applied to the root element of the template, the sys:attached=”dataview” will indicate that I will use the ASP.NET AJAX 4.0 DataView features together with the template. To make sure the DataView will get its data from the RentalWebDataService, the dataview:dataprovider attribute is used and its value is set to the RentalService.dataContext object, the DataView’s autofecth property is also set to true, to automatically fetch data. The fetchoperation property will specify which operation of the RentalWebDataServices should be used when the DataView fetches the data.

There are two ways to bind data within a template, for example the short {{ field }} expression or the {binding field} expression. As you can see I have used both expressions in the template, one for the background-color style (to bind a value to a specific style attribute, the sys:style-<style> attribute is used). The {{ ID }} and {{ Description }} shortcut will make sure to get the data from the Rental’s (The entity returned from the Rental operation of the RentalWebDataService ) ID and Description property. Take a look at the binding expression used for the <tr> background-color style:

<tr sys:style-background-color="{binding Status, convert=convertStatusToColor, ColorType=Name}">


There is now an option to specify a Converter, a method which will take the bounded value and pass it as an argument to the specified method and do a conversion and return a new whole value. The Status property in my case returns a string with different kind of status, Approved, NotApproved and Pending. What I want to do, is to convert those values into different colors as I mention earlier in my post. To do that I have used the new Converter feature. To set up a converter is easy just use the Sys.Binding.converters property and assign a method to it with two arguments, the value to convert and a binding argument (holds information about the binding).

Sys.Binding.converters.convertStatusToColor = function(status, binding)
{
     //do something then return the converted value
}

One great thing with the converter, is the possibility to use expandos, for example in my code I have added a ColorType expando to specify if the color that returned from the converter should be a name or not. The binding argument of the converter method can be used to get the expando, for example:

"{binding Status, convert=convertStatusToColor, ColorType=Name}"


Sys.Binding.converters.convertStatusToColor = function(status, binding)
{
    if( binding.ColorName == 'Name')
          //....
     //do something then return the converted value
}

I have created the ugliest converter method ever made, here it is:

Sys.Binding.converters.convertStatusToColor = function(status, binding)
{
       if (binding.ColorType == 'Name')
      {
             if (status == 'Approved')
                    return 'green';
                else if (status == 'NotApproved')
                    return 'red';
                else if (status == 'Pending')
                    return 'yellow';
                else
                    return 'white';
        }
        else
       {
             if (status == "Approved")
                 return '#00ff00';
             else if (status == "NotApproved")
                 return '#ff0000';
             else if (status == 'Pending')
                 return '#ffff00';
             else
                 return '#ffffff';
        }
}

Well, it’s a simple method to convert the incoming string, and return a color for the <tr>’s background-color. Here is the whole client-side code:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjax.js" type="text/javascript"></script> 
    <script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxTemplates.js" type="text/javascript"></script>
    <script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxAdoNet.js" type="text/javascript"></script>
    <script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxDataContext.js" type="text/javascript"></script>


    <script type="text/javascript">

        var RentalService = {};

        RentalService.dataContext = $create(Sys.Data.AdoNetDataContext,
                                         {
                                             serviceUri: "RentalWebDataService.svc",
                                             mergeOption: Sys.Data.MergeOption.appendOnly
                                         });


        Sys.Binding.converters.convertStatusToColor = function(status, binding) {

            if (binding.ColorType == 'Name') {

                if (status == 'Approved')
                    return 'green';
                else if (status == 'NotApproved')
                    return 'red';
                else if (status == 'Pending')
                    return 'yellow';
                else
                    return 'white';
            }
            else {
                if (status == "Approved")
                    return '#00ff00';
                else if (status == "NotApproved")
                    return '#ff0000';
                else if (status == 'Pending')
                    return '#ffff00';
                else
                    return '#ffffff';
            }
        }

    </script>
    
    <style type="text/css">
        .sys-template { display:none; }
    </style>

</head>
<body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView">
    
    <table sys:attach="dataview"
        class="sys-template"
        dataview:dataprovider="{{ RentalService.dataContext }}"
        dataview:fetchoperation="Rental"
        dataview:autofetch="true">

        <tr sys:if="$index==0">
            <td>Booking No</td>
            <td>Description</td>
        </tr>
        
         <tr sys:style-background-color="{binding Status, convert=convertStatusToColor, ColorType=Name}">
             <td>{{ ID }}</td>
             <td>{{ Description }}</td>
         </tr>
    </table>
    
</body>
</html>

Summary

In this blog post you have seen how to data bind and use the DataView to do client-side binding to a ADO.NET Data Service, you have also got introduced to the Microsoft AJAX NDC, if you want to get more information about the NDC, check out Scott Guthrie's blog: http://weblogs.asp.net/scottgu/archive/2009/09/15/announcing-the-microsoft-ajax-cdn.aspx, you have also seen the new Preview 5 converter feature.

To find more information about ASP.NET AJAX 4.0 Preview 5.0, you can check out my two earlier posts:

http://weblogs.asp.net/fredriknormen/archive/2009/09/11/asp-net-ajax-4-0-preview-5-available.aspx

http://weblogs.asp.net/fredriknormen/archive/2009/09/11/keep-the-first-empty-item-in-a-listbox-when-using-asp-net-ajax-4-0-preview-5-and-observer.aspx

Jim, Dave and Bertrand Le Roy’s posts on Preview 5:
http://weblogs.asp.net/jimwang/archive/2009/09/11/asp-net-ajax-preview-5-and-updatepanel.aspx

http://weblogs.asp.net/infinitiesloop/archive/2009/09/10/microsoft-ajax-4-preview-5-the-dataview-control.aspx

http://weblogs.asp.net/bleroy/archive/2009/09/14/building-a-class-browser-with-microsoft-ajax-4-0-preview-5.aspx

 

3 Comments

  • Very nice post mate. Your blog is starting to become "the" place to go for anything related to asp.net ajax 4.0 preview bits. At least you are my go to man when I need to clarify few things on the changes from one preview bits to another. So cheers and do keep it up.

    I have also tweeted about yours here:

    RT @velvetflair: ASP.NET AJAX 4.0 Preview 5 – Working with Converters and the new CDN http://3.ly/GKU

    Thanks,

    Shahriar Hyder


  • @vevletflair:
    Thanks :)


  • @JonW:
    JonW asked me why I didn't use a simple CSS class for the status, in that way I wouldn't need to use the Converter. That is true, but I wanted to demonstrate the use of the new Converter feature. Thanks for the tip, thought, was a good one!

Comments have been disabled for this content.