现在的位置: 首页 > 综合 > 正文

使用AJAX和ASP.NET来制作DropDownList

2012年04月15日 ⁄ 综合 ⁄ 共 7152字 ⁄ 字号 评论关闭

Introduction

 

[ Download Code Sample ]

In the first section of this article, we shall introduce AJAX and discuss its advantages and disadvantages. Next, we look at the XMLHTTPRequest object, its properties and functions, and how to create an instance of this object. Then, we will illustrate the use of AJAX functionality by creating a sample application. Finally, we will talk about how the sample application works. The sample application is an ASP.NET web application, written in C#, and is available for download.

What is AJAX ?

 

AJAXstands for Asynchronous JavaScript and XML. AJAX is not a new technology; it is a new way of combining existing technologies. What we do in AJAX is create an asynchronous request to the web server using client-side JavaScript and an XmlHttpRequest object, and map a function to be executed when the response is received. An asynchronous request means that the browser does not need to wait for the response after sending the request to the server. What we gain using AJAX is a responsive user interface, and we get this by sending a request to the web server for a small amount of information, as many times as we want, without sending the complete information on the form. In AJAX , the request is for data, not for a GUI element, so an AJAX request can be handled by an ASP.NET page without any HTML content, a custom HTTP module, or a web service. The core component in AJAX is the XMLHTTPRequest object. As many web developers are not familiar with this object, we will discuss it in detail in the next section. Following are the advantages and disadvantages of AJAX .

Advantages:

  1. The use of AJAX the increases the richness and responsiveness of the web page interface.

  2. It reduces the network traffic and CPU usage on web server. This is because there will be no post back to the server that will render a complete HTML page. For example, if you are displaying a lot of data in a web page, the HTML page size may be about 100 kilobytes. This big string has to be created on the server and then sent back to the client.

Disadvantages:

  1. The use of AJAX requires users to have JavaScript enabled on their browser. Because of this, an AJAX website should provide a non-AJAX alternative for users without JavaScript enabled.

  2. AJAXbreaks the normal browsers' Back button behavior. When a page is updated dynamically, returning to the previous state may not be possible, since browsers typically record only complete page requests in their history lists.

  3. As not all browsers are complying with W3C standards, AJAX applications have to be tested rigorously to deal with the quirks of different browsers.

The XMLHTTPRequest Object

 

The XMLHTTPRequest object is used to send a request to, and receive a response from, the web server. Using this object, the web page can make a request to the web server asynchronously, and receive a response asynchronously. Even though this object is not a W3C standard, most of the current browsers (IE5.0, Mozilla 1.0, Netscape 7.0, Safari 1.2, and Opera 8.0) have implemented this object. Hereafter I will also refer an XMLHTTPRequest object as an XMLHTTP object.

Properties and Functions of XMLHTTPRequest object used in the Sample Application

Table 1 – Properties of XMLHTTPRequest Object

Property

Description

onreadystatechange

The response handler function, which gets called for every change of the readyState property.

readyState

The state of the receiving request.

status

The HTTP status code returned by the server.

responseXML

The XML document returned by the server.

Table 2 – Methods of XMLHTTPRequest Object

Function

Description

open

Initializes a request.

send

Sends a request to the server.

Creating an Instance of an XMLHTTPRequest Object

While any browser-supported scripting language can be used to access this object, the method by which an instance of an XMLHTTPRequest object is created varies from browser to browser. Internet Explorer (IE) implements this object using ActiveX technology, so creating an instance of this object requires the use of “New ActiveXObject(ProgId)”, where ProgId is either Msxml2.XMLHTTP or Microsoft.XMLHTTP, depending on the version of MSXML installed. Mozilla, Safari, and Netscape implement this as a native object, so creating an instance requires the use of “New XMLHttpRequest()”. The following JavaScript function (Listing 1) creates an instance of an XMLHTTP object independent of browser type. The code presented for this article has been tested with IE 6.0, Netscape 8.0, and Mozilla Firefox 1.0.

Listing 1 – Creating an XMLHTTP Object

function CreateXmlHttp()

{

    //Creating object of XMLHTTP in IE

    try

    {

        XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

    }

    catch(e)

    {

        try

        {

            XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

        }

        catch()

        {

            XmlHttp = null;

        }

    }

    //Creating object of XMLHTTP in Mozilla and Safari

    if(!XmlHttp && typeof XMLHttpRequest != "undefined")

    {

        XmlHttp = new XMLHttpRequest();

    }

}

The Sample Application

 

The sample application uses a pair of DropDownList controls. A change in the selected value of the first drop-down list should populate the second drop-down list with a new collection of items. This paired behavior is found in many applications, such as a Country-State pair and a Category-Product pair. We have chosen to discuss the Country-State DropDownList pair. In traditional web applications, a change in the value of the Country DropDownList results in the web page posting back to server in order to populate the States DropDownList. In our example, we will populate the States DropDownList by retrieving state data from the server using AJAX , without submitting the entire form to the server.

In this section, first we will discuss the CountriesAndStates.xml and CountriesAndStates.xsl files, and then the CountryStateXml class which is used to get country and state data from the XML file. Next, we will discuss the start page of our project, which is AjaxClient.aspx. We will then discuss our JavaScript files, AjaxVariables.js and AjaxScript.js. You will find core AJAX code in the AjaxScript.js file. Finally we will talk about the AjaxServer.aspx page, which handles the AJAX requests.

CountriesAndStates XML and XSL Files

The CountriesAndStates.xml file stores the names of all countries and their states. The format of this XML file is shown below (Listing 2). Each country is represented as a single country node, and all of its states are represented as child nodes. At present this XML file has only three countries and some of the states of these countries. You can edit this XML to add other countries and states.

Listing 2 – CountriesAndStates.xml File

<country name=" USA">

    <state> Alabama</state>

    <state> Alaska</state>

    <state> Arizona</state>

    <state> Arkansas</state>

</country>

The CountriesAndStates.xsl file has the transformation logic for converting one form of XML into another form of XML. This transformation takes a country name as an input parameter, and returns its corresponding states in an XML string.

CountryStateXml class

The CountryStateXml class is used to get country or state data in different formats depending on the method called. This class has one constructor and three public methods.  The constructor loads the CountriesAndStates.xml file into an XPathDocument. The public method GetCountryList returns a list of countries as an ArrayList. The second method GetStateList returns a list of states for a given country as an ArrayList. The third method GetStatesXMLString returns an XML document containing all the states for a given country name, along with the country name.

AjaxClient Page

The start page of our sample application is AjaxClient.aspx and Figure 1 shows it viewed in a browser. This page has two DropDownList server controls. The HTML markup of this page is given in Listing 3. The onchange event of the Country DropDownList is tied to the JavaScript function CountryListOnChange and is shown in bold text in the following markup. We will discuss the CountryListOnChange function later in this section.

Figure 1 – AjaxClient.aspx Page in a Browser


Listing 3 – HTML of AjaxClient.aspx page

<form id="Form1" method="post" runat="server">

    <asp:DropDownList id="countryList" onchange="return CountryListOnChange()"

        style="Z-INDEX: 101; LEFT: 20px; POSITION: absolute; TOP: 28px"

        runat="server" Width="174px" Height="28px"></asp:DropDownList>

    <asp:DropDownList id="stateList"

抱歉!评论已关闭.