Chris Umbel

ADO.Net Data Services with jQuery

Lately I've been spending quite a bit of time messing around with ADO.Net Data Services. Thus far I'm pleased with it. Considering it sits nicely on top of EF models and I've been using EF for nearly all of my personal projects of late I've been able to glean a service layer with almost no work.

If there's one thing I'm not passionate about, however, it's web interface work. I'm very glad technologies like jQuery exist but I'm ecstatic it's other people's jobs to work with them. But, I have no choice but to do some web work on occasion. Whether it's for simple administrative tools at the office or even the development of this very website sometimes I simply must write web interface code.

With both of those concepts on the brain I decided to take a stab at consuming an ADO.Net data service from jQuery for a personal project I'm working on. The result. Easy as falling off a log.

To illustrate an example we have to start out with a web project containing an entity model. For those of you who are unfamiliar with generating models it's outlined here. In this case I'll just create a simple, single table model that will house the names of hockey players. Note that this will require downloading and including the jQuery and JSON javascript libraries into the project.

There isn't too much to do to get our service to work with our model. Just change the parent class of our service to employ our entity model in the constructed type and the access rules. Because this is just an example we'll allow the service to modify Player entities without restriction.

public class HockeyDataService : DataService<HockeyEntities>
{
	public static void InitializeService(
	    IDataServiceConfiguration config)
	{
      	config.SetEntitySetAccessRule("Players", EntitySetRights.All);
	}
}

That's it, our service is ready. Run your web project and it's good to go. The time has come to consume the service from client-side javascript on a web page. Here's a basic layout for a button to retrieve our list of players, provide a place to put the list, and a form to create a new player.

<button onclick="return getPlayers();">Get Players</button>
        
<div id="_players" style="width:400px;height:100px;">
</div>
        
<div id="_edit" style="position:absolute;width:400px;height:100px;
            left:200px;top:10px;">
        <input type="text" id="_firstNameTextBox" />
        <input type="text" id="_lastNameTextBox" />
        <button onclick="return addPlayer($('#_firstNameTextBox').val(), 
            $('#_lastNameTextBox').val());">Add</button>
</div>

Now for the magic. We're just going to use simple jQuery AJAX calls to our service with the HTTP verb GET to retrieve our players and POST to save a player as is outlined in the following script. I'm not going to cover it here, but the PUT and MERGE verbs can be used for updating while the DELETE is used for, you guessed it, deleting.

<script>
function getPlayers() {
    $("#_players").html("");

    $.ajax({
        type: "GET",
        url: "HockeyDataService.svc/Players",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            displayPlayers(data.d);
        },
        error: function(xhr) {
            alert(xhr.responseText);
        }
    });
    
    return false;
}

function addPlayer(firstName, lastName) {
    var player = { FirstName: firstName, LastName: lastName };

    $.ajax({
        type: "POST",
        url: "HockeyDataService.svc/Players",
        data: JSON.stringify(player),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            displayPlayer(player);
        },
        error: function(xhr) {
            alert(xhr.responseText);
        }
    });

    return false;
}

function displayPlayer(player) {
    $("#_players").html($("#_players").html() + "<div>" + 
        player.FirstName + " " + player.LastName + "</div>");
}

function displayPlayers(players) {
    for (var i in players) {
        displayPlayer(players[i]);
    }
    return false;
}

</script>

And that's pretty much all there is to it. Most of the data access and service layers were auto generated. Not too shabby for such a small amount of work.

Fri May 29 2009 12:05:18 GMT+0000 (UTC)

Follow Chris
RSS Feed
Twitter
Facebook
CodePlex
github
LinkedIn
Google