Creating an Album List with Ajax and C#

Written By: Jay

- 20 Jun 2006 -
















Description: Over the past few months I have been toying with Ajax and .NET via the AJAX.NET Pro Library. I recently had a specific task to complete and it seemed to be a perfect candidate for Ajax. The task was very simple, get a list of Albums by an Artist. This functionality is of course part of a much larger on-line music app I was constructing but I needed to start with something small. The UI was very simple a TextBox to enter an Artists' Name and a Table to display the Albums.

  1. Objects and Data
  2. Diving In
  3. Ajax and the UI
  4. The Next Level
  5. Conclusion and Pitfalls

Part 3: AJAX and the UI

The next part is to hook up our search methods and results object to AJAX.

In the HTML we have already created the our controls so now we need some JavaScript functions:

First create a variable for the matched items (search results).

var matchList = document.getElementById("matches");

Next create a function that will be called by the onKeyUp event.

function GetArtist(searchCriteria) {
if (searchCriteria) {
 
WebForm1.GetArtist(searchCriteria, GetArtist_CallBack);
} else {
//clear the states dropdown
matchList.style.visibility = "hidden";
}
}

You'll have noticed a GetArtist_CallBack function that AJAX will pass it's response to.

This next block of code is the bread and butter of this whole app.

First we are checking for any errors.

Then we check to see if we got any results from our search and if we didn't we are going to hide our Select Box (matchList).

Provided that we get some results we will make the matchList visible, clear out any previous results and then set the number of items to the number of search results.

The last this we do is the tricky part. We are iterating over the results and we are inserting the items into our matchList as Options with a text of Artists Name and a value of the ArtistID.

Javascript:

function GetArtist_CallBack(response)
{
//if the server side code threw an exception
if (response.error != null)
{
alert(response.error); //we should probably do better than this
//return;
}
 
//if we didn't get what we expect, or didn't get any matches
if (!response.value[0] || response.value[0].length == 0)
{
matchList.style.visibility = "hidden";
return;
}
 
matchList.style.visibility = "visible";
matchList.options.length = 0; //reset the states dropdown
matchList.size = response.value.length; //dynamically set the size of 
the select box
 
for (var i = 0; i < response.value.length; ++i)
{
matchList.options[matchList.options.length] = new 
Option(response.value[i].artistName,response.value[i].artistID);
}
}

If all has gone well you should be able to start typing in a name and some results should show as a select box. Once you have some results in the select box clicking on one will invoke a second AJAX function that will get Albums by ArtistID.

<< Previous

Next >>