Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using the AJAX Library

After you understand the basics of AJAX, you can start applying this knowledge to your projects. In this section, you learn how to use AJAX to connect two dropdown list boxes in ASP.NET.

This example allows you to select a make of car (BMW, Mercedes, or Porsche) and use AJAX to request the models for the selected car make. The very simple page is illustrated in Figure 1.1.

Figure 1.1

Figure 1.1 AJAX dropdowns

When you select a car from the first dropdown, an AJAX request is made to the server to get different car models. For this example, a call is be made to a page called getModels.aspx, which is defined in Listing 1.4.

Listing 1.4. getModels.aspx

<%@ Page Language="C#"%>


<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        string Make = Request.QueryString["make"];
        switch (Make.ToUpper())
        {
            case "BMW":
                Response.Write("<models><car>3-Series</car>
<car>5-Series</car><car>7-Series</car><car>M</car><car>X3</car>
<car>X5</car><car>Z-Series</car></models>");

                break;

            case "MERCEDES":
                Response.Write("<models><car>C-Class</car>
<car>E-Class</car><car>S-Class</car><car>AMG</car></models>");

                break;

            case "PORSCHE":
                Response.Write("<models><car>911</car><car>Cayman</car>
<car>Cayanne</car><car>Boxster</car></models>");

                break;

            case "BLANK":
                Response.Write("<models><car></car></models>");
                break;

            default:
                Response.Write("<models><car>Invalid selection</car></models>");

                break;

        }

    }
</script>

This page simply accepts a query string argument called make and will return an XML string of car models, depending on the make argument. A sample of the returned XML where the value PORSCHE is passed into the make query string argument is described in Listing 1.5.

Listing 1.5. Models XML Records

<models>
    <car>911</car>
    <car>Cayman</car>
    <car>Cayanne</car>
    <car>Boxter</car>
</models>

Now that you have learned where the data is coming from, it is time to learn how to request and manipulate the data using AJAX. Listing 1.6 describes a page named AjaxDropdowns.aspx.

Listing 1.6. AjaxDropdowns.aspx

<%@ Page Language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        //setup the AJAX call on the dropdown
        ddlMakes.Attributes.Add("onchange",
"javascript:createAjaxRequest('getModels.aspx', '?make=' + " + ddlMakes.ClientID +
".value);");

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>

</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:DropDownList ID="ddlMakes" runat="server">
            <asp:ListItem Value="blank">Select a Make</asp:ListItem>
            <asp:ListItem>BMW</asp:ListItem>
            <asp:ListItem>Mercedes</asp:ListItem>
            <asp:ListItem>Porsche</asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="ddlModels" runat="server">
        </asp:DropDownList>
    </div>
    </form>
    <script type="text/javascript">
    //Section 1
    var http_request = false;

    function createAjaxRequest(url, parameters) {
      http_request = createHttpRequestObject();

      if (!http_request) {
         alert('Error creating XMLHTTP object');
         return false;
      }
      http_request.onreadystatechange = getResponse;
      http_request.open('GET', url + parameters, true);
      http_request.send(null);
    }

    //Section 2
    function createHttpRequestObject(){
        var request;
        if (window.XMLHttpRequest) { // IE7, Mozilla, Safari, etc.
             request = new XMLHttpRequest();
             if (request.overrideMimeType) {
                request.overrideMimeType('text/xml');
             }
          } else if (window.ActiveXObject) { // IE 6 and previous
             try {
                request = new ActiveXObject("Msxml2.XMLHTTP");
             } catch (e) {
                try {
                   request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
             }
          }

          return request;
    }

    //Section 3
    function getResponse() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //get dropdown
            var ddl = document.forms[0].<%=this.ddlModels.ClientID %>;

            //clear items in dropdown
            ddl.options.length = 0;

            //get the XML response and loop elements
            var xmldoc = http_request.responseXML;
            var cars = xmldoc.getElementsByTagName('car');
            for(i=0; i<cars.length; i++){
                //add items to the dropdown
                try{
                    var opt = new
Option(cars[i].firstChild.nodeValue, cars[i].firstChild.nodeValue);
                    ddl.add(opt, i);
                }
                catch (e){
                    ddl.length=0;
                }
            }
            http_request = null;
         }
         else {
            alert('There was a problem with the request.');
         }
      }
    }

</script>
</body>
</html>

As you browse through the code in Listing 1.6, first notice that it is using the simple AJAX library that you learned about earlier in this chapter. You learn about the changes that were made to the getResponse function later in this chapter, but it is important to note because you will also see calls made to the createAjaxRequest function, which is discussed next.

This page contains two dropdowns, ddlMakes and ddlModels, and one server side event handler, Page_Load. When the user selects a car make from the ddlMakes dropdown, an AJAX call needs to be made to populate the ddlModels dropdown with car models. In this example, the AJAX call is set up on the ddlMakes dropdown in the Page_Load event by adding an onchange attribute to the server side dropdown list control and setting its value to call the createAjaxRequest JavaScript method defined in the simple AJAX library.

The big change to the AJAX library is in the getResponse method, which is highlighted in Listing 1.7.

Listing 1.7. getResponse Method

function getResponse() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //get dropdown
            var ddl = document.forms[0].<%=this.ddlModels.ClientID %>;

            //clear items in dropdown
            ddl.options.length = 0;

            //get the XML response and loop elements
            var xmldoc = http_request.responseXML;
            var cars = xmldoc.getElementsByTagName('car');
            for(i=0; i<cars.length; i++){
                //add items to the dropdown
                try{
                    var opt = new
Option(cars[i].firstChild.nodeValue, cars[i].firstChild.nodeValue);
                    ddl.add(opt, i);
                }
                catch (e){
                    ddl.length=0;
                }
            }
            http_request = null;
         }
         else {
            alert('There was a problem with the request.');
         }
      }
    }

As you walk through the method, first, a reference is made to the ddlModels dropdown on the page, and all items are cleared by setting the options.length property to zero. If you don’t do this, items will simply get added to the dropdown list every time the user selects a new car make. Next, the XML response is returned from the http_request object. Finally, the code loops through the values of all the returned <car> elements and populates the ddlModels dropdown list.

When you execute the page, you will notice that the dropdown is populated with data very quickly with no page flicker. This is a great first example of using AJAX because linked (or related) dropdowns are a common scenario that you see in applications. Additionally, functionality such as this is often a developer’s first experience with AJAX functionality in their applications.

Before ASP.NET AJAX (and other libraries), this was how we, as a development community, had to write AJAX functionality. One of the first things you will notice about this approach is the amount of JavaScript that you have to write and maintain. It quickly becomes very difficult to maintain and add or change the functionality of your pages without starting from scratch. There is nothing wrong with this approach, and libraries such as ASP.NET AJAX shield you from a lot of the coding and JavaScript maintenance (and the libraries are generating this code for you). However, it is important to note the maintenance cost associated with manually writing AJAX code.

  • + Share This
  • 🔖 Save To Your Account