Rants and Raves

Thanks for visiting my blog!

WCF Data Services and jQuery
WCF Data Services and jQuery
February 23, 2010

Url: http://wilderminds.blob.core.windows.net/downloads/dataservicejque…

I’d recently been asked by Chris Sells to help him with a simple WCF Data Services/jQuery example so I thought I’d share it via my blog as well. The basic idea is to use jQuery’s AJAX functionality to retrieve JSON instead of the usual OData and consume it on a web page.

The example I decided on using is to expose the XBox database with paging. I am not doing any of the niceties like getting result counts to show a real navigation bar.  Instead this is quick and dirty to simply do “next” and “prev” and use WCF Data Service’s URI API to retrieve data.

Like most of my XBox examples, I am using the Entity Framework to simply expose three entities types (Games, Genres and Ratings). Then I utilize a WCF Data Service to expose these types for consumption via REST.  My HTML is simple:

<h2>
  XBox Games</h2>
<div>
  <a href="#" id="PrevPage">Prev</a>
  <a href="#" id="NextPage">Next</a>
</div>
<div id="gameTable" />

The gameTable will simply be filled with a simple TABLE element for our data. So to the jQuery we go.  I am using plain jQuery 1.3.2 (though plugins could be used to simplify some of this code, I choose to just do it raw for simplicity).

First I set up a couple of variables to hold our paging information:

// globals for paging
var page = 0;
var pagesize = 25;

Next I handle the document’s ready function to do some work when the initial page load is complete:

// Loads once the document has completed loading
$(document).ready(function () {
  
  // Set up paging buttons
  $('#PrevPage').click(function (evt) {
    // Stop the navigation from happening
    evt.preventDefault();
    if (page > 0) {
      page--;
      loadData();
    }
  });
  $('#NextPage').click(function (evt) {
    evt.preventDefault();
    page++;
    loadData();
  });
  
  // Load the initial data
  loadData();
});

When setting up the paging buttins, I use the ‘#PrevPage’ and ‘#NextPage’ CSS selectors to find items named PrevPage and NextPage and wire up the event to cause the page changes to happen.  The ‘evt.preventDefault()’ call stops the buttons from trying to navigate since we’re using them as buttons.  FInally once we change the current page value, we call loadData (or in the initial case, call loadData with the default values).

function loadData() {
  var url = "/GameService.svc/Games?$orderby=Name" +
             "&$skip=" + (page * pagesize) + 
             "&$top=" + pagesize;
  $.ajax({
    type: "GET",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
      loadTable(msg.d);
    }
  });
}

In the loadData function, I first create the URL by using the Data Service/OData URL API to retrieve games by Name while using the global values to retrieve a page of data at a time (see the $skip and $top parameters). Once the URL is defined, jQuery’s ajax function executes the URL and returns in the success function in which we call loadTable to create the table for us. Since the returned JSON is contained in a ‘d’ element for security, we de-reference the ‘d’ element before we sent it into the loadTable function.

function loadTable(results) {
  var table = '<table><thead><tr><th>Name</th>' + 
              '<th>Publisher</th><th>Box</th></thead><tbody>';

  for (var post in results) {
    var row = '<tr>';

    row += '<td>' + results[post].Name + '</td>';
    row += '<td>' + results[post].Publisher + '</a></td>';
    row += '<td><img src="' + results[post].ImageUrl + 
           '" style="width: 100px; height=150px" /></td>';

    row += '</tr>';

    table += row;
  }

  table += '</tbody></table>';

  $('#gameTable').html(table);

}

Finally in loadTable some simple HTML construction goes on to create a table with our results.  The for loop returns a iterator for each row in the collection which we can use to retrieve the individual item (see results[post].Name as an example). Once the table is built, it replaces the contents of the element named gameTable with the new table.

Because WCF Data Services will return JSON as well, you can use it to do AJAX work just as effectively as Silverlight can consume it for rich client work.  You can get the code here:

http://wilderminds.blob.core.windows.net/downloads/DataServiceJQuery.zip