Responsive User-interface Revisited

Implementing AJAX-enabled Applications

UI Tips

LANGUAGES: C#

ASP.NET VERSIONS: 2.0

 

Responsive User-interface Revisited

Implementing AJAX-enabled Applications

 

By Andrew Flick and Devin Rader

 

In our April column Responsive User-interface we introduced the concept of combining the Microsoft XMLHTTP parser object with client-side script to create highly responsive Web user interfaces. This technique, which has come to be known as Asynchronous JavaScript and XMLHTTP (AJAX), gives you the power to make out-of-band callbacks from the client browser to the Web server, retrieve data, and then parse that data on the client. The advantage of this technique is that it allows you to avoid the postback which you would normally have to endure in order to retrieve data from the server side.

 

This month we will continue with the topic of AJAX and demonstrate some of the options available to you that make implementing AJAX-enabled applications even easier. We will look at some of the different AJAX libraries that are available and how you can use them to easily add AJAX functionality to your Web pages. Finally, we will look at the client-side callback features that are built into ASP.NET 2.0.

 

AJAX Components

With the rise in popularity of AJAX, several community-based (and usually open source) projects have surfaced that attempt to roll the complex pieces of the XML parser and JavaScript into a single easy-to-use component. Components like this now exist for ASP.NET, ASP, PHP:

 

ASP.NET: http://sourceforge.net/projects/ajaxnet-library

PHP & ASP: http://cpaint.sourceforge.net/

 

Additionally, a number of JavaScript libraries that work independent of the server-side technology are available, including a project from Google:

 

http://dojotoolkit.org/

http://goog-ajaxslt.sourceforge.net/

 

Finally, even Microsoft has jumped on the bandwagon, announcing that in addition to its client-side callback features that have been included in ASP.NET 2.0, they will be releasing an AJAX library.

 

Introducing Ajax.NET

One of the most prominent AJAX libraries for ASP.NET is Ajax.NET, written by Michael Schwarz. This easy-to-use library allows you to quickly add AJAX functionality to your application. The component is extremely powerful, allowing you to pass both simple and complex data types.

 

At a high level, the Ajax.NET component works by exposing methods that are marked as AJAX-enabled (using the AjaxMethod attribute) on the client side. This is done via an HTTP Handler that dynamically generates the necessary JavaScript at run time. Exposing the server-side AJAX methods as client-side functions is what allows you to initiate the callback.

 

To get started using the Ajax.NET Library, start by adding a reference to the Ajax.NET component to your ASP.NET project. Next, you need to add the reference to the Ajax.NET HttpHandler to the project s web.config file. This handler is used to generate the JavaScript needed to process the callbacks.

 

Then, in the Page_Load event, you need to tell the Web page to register any methods that have been marked as AJAX-enabled by executing the RegisterTypeForAjax method, as shown in the code below. This method is what tells Ajax.NET in which class it will find methods that it needs to expose to the client, and generates the necessary information for exposing the server-side methods to the client-side:

 

private void Page_Load(object sender, System.EventArgs e)

{

 Ajax.Utility.RegisterTypeForAjax( System.Type.GetType("AjaxDemo.WebForm1") );

}

 

The method requires that you pass the Type of the object that contains your AJAX-enabled methods into it. This means that you can expose methods in any class that can be referenced in your project. For simplicity sake, the AJAX-enabled methods in the articles samples all exist in the same Web page class named WebForm1.

 

Once these steps are completed, you simply need to create some server-side methods to expose to the client. Start by creating a simple method that adds two numbers and returns the result. This is shown in the code below:

 

[Ajax.AjaxMethod()]

public int ServerSideAdd(int firstNumber, int secondNumber)

{

 return firstNumber + secondNumber;

}

 

This is a simple sample that takes two integer values as arguments, adds them, and returns the resulting value.

 

In order to initiate the client-side execution of this method, simply add the JavaScript to call the method. Remember, this is possible because we called the RegisterTypeForAjax method in our page load, which told the Ajax.NET Library to create a JavaScript function for our ServerSideAdd method and emit that to the client. This method emitted to the client is what actually performs the callback to the server.

 

Next, you need a way to execute the client-side ServerSideAdd function. The next code sample shows how you could use the client-side OnClick event of a Button to execute the function:

 

 

     

 

 

     

        

              onclick="WebForm1.ServerSideAdd(100,99,ServerSideAdd_CallBack);"

              type="button" value="Button">

     

 

 

The sample code provides the required integer arguments to the method, but it additionally supplies the name of a client-side callback function that will be executed once the server-side processing has completed. This client-side callback function is what allows us to retrieve the value that is returned by the server-side method. In this case, the callback method simply displays the response value in an alert dialog box.

 

Other Ajax.NET Features

So far you have seen how easy it is to add simple AJAX functionality to your Web applications using Ajax.NET. The component supports a variety of advanced AJAX options, including passing complex data types between client and server, requiring session state between requests, operating HTTP or HTTPS, and even caching the return values of AJAX methods to increase application performance.

 

Passing complex data types, such as DataSets, DataTables, custom collections, and arrays of simple types between client and server is natively supported by Ajax.NET. The code sample available for download demonstrates this (see end of article for download details), showing how you can create an application that allows the user to navigate the Customer | Order | Order Detail relationship in the Northwind database.

 

Asynchronous Callback Features in ASP.NET 2.0

While components like Ajax.NET give you powerful capabilities that can be used with technology available today, ASP.NET 2.0 offers similar functionality as a native part of the .NET 2.0 Framework. The figure below shows how client-side callbacks work in the ASP.NET framework.

 


Callback handling can be added to any of the in-box ASP.NET controls, as well as baked into custom server controls. In order to enable callbacks, you implement the System.Web.UI.ICallBackEventHander interface. This interface requires you to implement a single method, RaiseCallbackEvent. This is the server-side event that fires when the client executes the callback. After you implement the interface, you want to tie your client-side events back to the server. You do this by using the Page.ClientScript.GetCallbackEventReference method. This method allows you to specify the two client-side functions: one to serve as the callback handler and one to serve as an error handler. The following code sample demonstrates how you can extend the in-box TextBox control by modifying the control s Render method to emit the necessary client script, and implementing the ICallbackEventHander interface, adding the RaiseCallBackEvent method to use callbacks to perform some data validation:

 

protected override void Render(HtmlTextWriter writer)

{

 output.AddAttribute("OnBlur", "ClientCallback();");

 this.AddAttributesToRender(writer);

 base.Render(output);

}

protected override void OnPreRender(EventArgs e)

{

 Page.ClientScript.RegisterStartupScript(

     typeof(Page), "ClientCallback",

     "function ClientCallback() {" +

         "args=document.getElementById('" + this.ClientID + "').value;" +

         Page.ClientScript.GetCallbackEventReference(this, "args",

             "CallbackHandler", null,"ErrorHandler",true) + "}",

     true);

}

#region ICallbackEventHandler Members

public string RaiseCallbackEvent(string eventArgument)

{

 int result;

 if (!Int32.TryParse(eventArgument,out result) )

     throw new Exception("The method or operation is not implemented.");

 return "Valid Data";

}

#endregion

 

As you can see, the client-side OnBlur attribute will be rendered to the TextBox. We will use this client-side event to trigger the execution of the callback to the server. In this sample, the ClientCallback function, which is executed when the OnBlur event fires, is used to populate the client-side args variable and then initiate the actual client-side callback function. The ClientCallback function is created and rendered during the PreRender event.

 

Inside the ClientCallback function we are generating, you use the Page object s GetCallbackEventReference method to generate the client-side script that actually initiates the callback. The parameters passed to this method indicate which server control is initiating the callback, the names of the client-side callback functions, and the name of the callback function parameter variables.

 

In the code, the two client-side callback functions referenced are CallbackHandler and ErrorHandler. As their names indicate, CallbackHandler will be executed if the server-side code returns successfully, while ErrorHandler will be called if an error occurs during the serve-side execution. The two function parameters are args and ctx.

 

In addition to the server control code changes, the two client-side callback functions must be added to the Web page. The following example shows these functions:

 

var args;

var ctx;

function CallbackHandler(args,ctx)

{

 alert("The data is valid");

}

function ErrorHandler(args,ctx)

{

 alert("Please enter a number");

}

 

If you add this control to a Web page and view the page in the browser, as soon as the TextBox loses focus, the page performs a client-side callback to validate the data. The callback raises the RaiseCallbackEvent method on the server, which validates the value of the TextBox that was passed to it in the eventArguments. If the value is valid, it returns a string and the client-side CallbackHandler function fires. If the value is invalid, it throws an exception, which causes the client-side ErrorHandler function to execute.

 

Conclusion

AJAX technology is rapidly becoming a powerful tool in the development toolkit of many developers. Thankfully many different utilities exist that make implementing AJAX functionality in your Web application easy. As was demonstrated here, using the Ajax.NET component in your ASP.NET applications is an easy and powerful way to add AJAX features. This free and open source component is a great way to give your end users a richer and more responsive user interface. Even if you are not developing in ASP.NET, there are lots is great solutions available to you.

 

Finally, we looked at how ASP.NET 2.0 is taking the XMLHTTP technology and making it an integral part of the .NET Framework. By adding this functionality directly to the framework, it makes adding client callback features to your ASP.NET applications even easier.

 

With that, we remind you to e-mail your questions to us at [email protected].

 

The sample code referenced in this article is available for download.

 

Andrew Flick is Product Manager of NetAdvantage Windows Forms Technologies & TestAdvantage for Infragistics, Inc., a Microsoft Visual Studio Industry Partner. He is responsible for spearheading product management and strategies of Infragistics Windows Forms product line - working directly with the Director of Development to set the direction, plan, and manage product development. Andrew is a Microsoft .NET MVP and is the chair of the INETA Academic Student Committee. Contact Andrew at mailto:[email protected].

 

Devin Rader is an Infragistics Technology Evangelist and is responsible for authoring Infragistics reference applications and .NET technology articles, as well as the world-wide delivery of Infragistics technology demonstrations. Devin is an active member and leader for INETA, has served as the sole technical editor for numerous works, and is a contributing author for the soon to be published ASP.NET 2.0 Professional. Contact Devin at mailto:[email protected].

 

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish