Connecting to ASP.NET

ASP.NET is an extremely powerful programming platform. Here, we will learn how to make a connection to it with an Ajax request. The sample was created with Visual Studio, and we will simply run it in Debug mode in this example, but it can be configured to run in Windows IIS if you prefer.

The first thing that we will need to do in order to start our example is create a new C# website. After we have created our new C# website, we need to move the Utilities, AjaxUpdater, HTTP, and Ajax JavaScript files to the project directory. We will then need to import them into the Default.aspx file that is created in the project by default when we create the website (see Listing 21.1).

Listing 21.1. Importing the Appropriate JavaScript Files (Default.aspx)

<script type="text/javascript" src="/books/1/87/1/html/2/javascript/Utilities.js"></script> <script type="text/javascript" src="/books/1/87/1/html/2/javascript/model/AjaxUpdater.js"></script> <script type="text/javascript" src="/books/1/87/1/html/2/javascript/model/HTTP.js"></script> <script type="text/javascript" src="/books/1/87/1/html/2/javascript/model/Ajax.js"></script>

After the files are imported, we will add the code in Listing 21.2 to handle the HTML that will take input from a user and make a request to the server side.

Listing 21.2. Taking User Input (Default.aspx)

<form  runat="server"> <div>Request:</div> <div><input type="text" autocomplete="off" onkeyup="request(this.value);"/></div> <br /><br /> <div>Response:</div> <div ></div>  </form>

The user will use the request input field to enter a value, which will then make a request to the server side. After the response is received, it will be displayed in the div with an id of response. The request to the server side happens in a JavaScript method, which is conveniently named request. Take a look at the request method in Listing 21.3.

Listing 21.3. Making a Request to the Server Side (Default.aspx)

<script type="text/javascript">         function request(data)         {             AjaxUpdater.Update('GET', 'serviceConnector.aspx?request='+ data, onResponse);         }  </script>

The request method takes a parameter named data, which is the value of the input field. This value is passed to it each time the keyup event is fired. The method then makes an XHR via the GET method to a file named serviceConnector.aspx. The data parameter is appended to the URL and passed as a query value to the request key. Finally, a method named onResponse is added as the callback method and the request is made via the AjaxUdpdater's Update method. The onResponse method will be added to this file after we know what data will be received from the response and we understand how to properly parse it. The serviceConnector.aspx file connects the front end to the C# code, which we will write in a moment. This C# code will receive the request and respond with a username that contain the letters that are entered into the input field. Before we create the C# code behind, let's take a look at the serviceConnector.aspx in Listing 21.4.

Listing 21.4. Bridging the Gap Between the Front End and Server Side (serviceConnector.aspx)

<%@ Page ContentType="text/xml" Language="C#" AutoEventWireup="true" CodeFile="serviceConnector.aspx.cs" Inherits="serviceConnector" %>

This file is the link between the front-end and the back-end code. The two most important things to remember are to have only this line of code in the file (otherwise the response will not be valid), and to make sure to add the ContentType property. This property does not exist by default when the file is created and without it the response will not be valid XML.

The way this file works is that it receives the request and passes the data to the code behind. The code behind, which is the C# class that contains the code that handles the request, is defined in the CodeFile property. This class will take the request, process it through any custom methods we define, and return a response based on the logic we define. In this case, the C# class that we create will simply receive the request, search an array of usernames, and return a username as a string value. The username that is returned will be formatted as XML and delivered as the response to the Ajax engine and, ultimately, the onResponse callback method that we defined in the AjaxUpdater request. Let's take a look at Listing 21.5 to see the C# code behind for the serviceConnector, understand what classes it needs to import, and how it performs the username searches.

Listing 21.5. The Code Behind the serviceConnector (serviceConnector.aspx.cs)

[View full width]

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml; public partial class serviceConnector : System.Web.UI.Page {     protected void Page_Load(object sender, EventArgs e)     {         this.SearchUsers();     }     private void SearchUsers()     {         string request = Request["request"].ToString();         string usernameXml = "";         string[] usernames = new string[3] { "Kris Hadlock", "Grace Hopper", "Pi Sheng" };         foreach(string username in usernames)         {             if(username.ToLower().Substring(0, request.Length) == request.ToLower())             {                 usernameXml += "<username>" + username + "</username>";             }         }         usernameXml = "<?xml version='1.0' encoding='iso-8859-1' ?><usernames>" +  usernameXml + "</usernames>";         XmlDocument xDoc = new XmlDocument();         xDoc.LoadXml(usernameXml);         xDoc.Save(Response.OutputStream);     }  }

Aside from the default classes that are automatically imported via Visual Studio's new file option, we needed to import the System.xml class. This class will allow us to return a valid XML response to the client side. The first method fired in this class is Page_Load, which immediately calls the SearchUsers method. This is where all the action happens. The first thing we do is gather the request query that was sent. This is done by using the request method, targeting the request key, and converting it to a string. This string is set to a local string named request to later be used to perform the search. Next we define a string variable named usernameXml and construct an array of strings with three values named usernames. The three values may look familiar because they are usernames we have used in other samples throughout the book. After this array is constructed, we will iterate it and check to see whether any of the usernames begin with the request value. If they do, the names will be appended to the usernameXml string between username XML elements and CDATA to ensure they can be parsed properly if they contain any HTML of special characters. After we are finished iterating the usernames array, we will add an XML declaration to the beginning of the usernameXml string and nest the existing usernameXml string values with usernames elements. Although we have an XML string defined, this will not be enough to return as valid XML to the client side. This is where the System.xml class comes in handy. We need it to instantiate the XmlDocument object, call its LoadXml method, and pass the usernameXml string to it. This will provide us with a valid XML structure, which can now be returned to the client. In order to return this data, we cannot simply use a return as we do in PHP. We must fire the XmlDocument object's Save method and pass the following parameter, Response.OutputStream. This will output the XML data and return it as the response to the client-side callback method.

Now that we will be receiving the response on the client side, we need to create the onReponse method to handle it. Listing 21.6 shows how this method will receive the response, parse the data, and display the data in the response div.

Listing 21.6. Handling the Response (Default.aspx)

[View full width]

function onResponse() {         if(Ajax.checkReadyState('response') == "OK")     {         var usernames = Ajax.getResponse().getElementsByTagName('username');         for(var i=0; i<usernames.length; i++)         {             Utilities.getElement("response").innerHTML += usernames[i]  +"<br/>";         }     }  }

This method is quite simple because it follows all the responses we have created in other samples. Targeting the response and parsing the username data from the XML define a username variable. After we have defined the username, we simply write it to the response element and test our application. In order to test the application, we need to set Debug to true in the Web.Config file, which should be asked of us if we forget when we press the Debug button for the first time. After the application is up and running in a browser, we can test it by simply typing in the first letters in a name and seeing the response. Let's do the same thing with ColdFusion.

Ajax for Web Application Developers
Ajax for Web Application Developers
ISBN: 0672329123
EAN: 2147483647
Year: 2007
Pages: 129
Authors: Kris Hadlock

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: