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.
Part 1: Objects and Data
The first thing we need to do is add an Ajax "Auto-Complete" like function to a TextBox. This type of example is covered in more detail here The "Auto-Complete" functionality is very simple: A user starts typing in the search text box. The Search box has an "OnKeyUp" JavaScript Event defined. This JS Event triggers a function that sends the letters in the text box to an ASP.NET function. The ASP.NET function processes the query and returns the results to the JS function. The JS function them binds the results to Select Box.
One thing I have found with this is that results are bound to the value attribute of the Select/Option as well as the text value:
Metallica
This results in the Select box using the display text as the value as well. This may work for some apps but without a value we only have the Artist Name(s) to use for our second AJAX function. The second function will be to search for a list of albums by the selected artist. Since the data is normalized, the Albums table is linked to the Artists table via the ArtistID. This requires a little hacking.
What we need is a Select Box that looks like this:
Metallica Megedeth Ozzy
Binding data to the value attribute requires returning the Artist Search results as an Object Array.
This requires us to create an Serializable Artist object using the [Serializable] attribute at the start of the class. This will allow us to return an ArrayList of Artists but Serialized in XML so the browser can read them.
[Serializable] public class EmployeeObject
The second part of this task is to get the Albums based on the Artist ID. This part requires invoking an AJAX call that will send the selected ArtistID to the back-end (WebService, XML DataSet, SQL) to get the Albums and then display the results in as an html table.
*NOTE: I first tried to bind my results to a DataList but this resulted in JavaScript Errors and a blank DataList. This will not work because a DataList in a .NET Server Control and JavaScript/AJAX is Client-side control. The trick is to bind the results to a string array in JavaScript and then bind that to a DIV.