JavaScript with ASP.NET 2.0 Pages - Part 2

Published: 14 Feb 2007
By: Xun Ding

ASP.NET provides a number of ways of working with client-side script. This article explores the usage and drawbacks of ASP.NET script callbacks, and briefly presents a bird's view of ASP.NET AJAX.

Introduction

ASP.NET server-based web forms use a request-response model. Each request results in a roundtrip a.k.a postback to the server. Each postback causes the requesting page to be refreshed, regardless of the nature or the sender of the request. With web users becoming more and more sophisticated, the request-response-refreshing (or click-n-wait) model becomes less and less desirable and in the case of heavy webpages, the lack of smooth performance simply drives users away.

To remedy this, ASP.NET allows various ways to work with JavaScript. One class of them is the ClientScript class, which interjects JavaScript into a webpage, to perform a host of pure client-side tasks, such as window pop-ups, setting focus etc. This class uses strictly a server-centric model, in which the server controls the operation.

Another option is to use an object called XMLHttpRequest to bridge across server and clent-side script, and to enable client-side script to make direct calls to the server, retrieve server-side data, then partially and selectively refresh the calling page. With this model, ASP.NET enables you to create both server-centric and client-centric applications.

There are two ways from the client-side script to make server calls and achieve partial page rendering. One is using the ASP.NET built-in script callback mechanism, the other is the AJAX technology. In this article, we'll examine the Script Callback techniques in detail, we'll also briefly look at AJAX in general, and the programming models in ASP.NET AJAX.

ASP.NET JavaScript Callbacks

To shield programmers from the intricacies of making use of the XMLHTTP object, ASP.NET introduces a string of operations on the server and client side to accomplish Script Callbacks.

On the server side, the code-behind page class must define a method called GetCallbackEventReference method, it also must implement the ICalbackEventHandler interface. The ICalbackEventHandler interface requires two methods:

  1. RaiseCallbackEvent
  2. GetCallbackResult
The former method handles the necessary operation on the server such as data retrieval; the latter returns the result to the calling script.

Generally we define the GetCallbackEventReference method in the web form's Page_Load event. It returns the JavaScript command WebForm_DoCallback that is to be executed once the server has finished serving the call. The WebForm_DoCallback in turn is stored in the resources of the system.web assembly and will be retrieved through the WebResource.axd HTTP handler.

On the client side, at least two methods must be defined. The first one is the event handling method, responding to an event such as onclick, onmouseover; the second is used to process the response from the callback, and accordingly update's the necessary part of the page.

To illustrate these rather convoluted procedures, we use an example that provides suggestions based on user's input in a textbox. (Please note, this ASP.NET code is tailored from the original AJAX code written in ASP and JavaScript at http://www.w3schools.com/ajax/ajax_example_suggest.asp.)

Web form:
<form id="form1" runat="server">
  First Name: <input type=text name=tFirstName onkeyup="GetHint();"/>
</form>
<p>Suggestions: <span id="txtHint"></span></p>
Server-side Code
using System;
using System.Web.UI;

//implement ICallbackEventHandler Interface
public partial class scriptcallback : System.Web.UI.Page, ICallbackEventHandler
{
  private String hint;
  public String getHintFromServer;
    
  //Define GetCallbackEventReference method
//
whose signature is as the following: //public string GetCallbackEventReference( //Control target, //string argument, //string clientCallback, //string context, //string clientErrorCallback, //bool useAsync) void Page_Load(object sender, System.EventArgs e) { getHintFromServer = this.ClientScript.GetCallbackEventReference (this, "message", "ShowHint", "null", "null", false); } //The parameter eventArg is the argument parameter of //the GetCallbackEventReference,passed from the JavaScript. void ICallbackEventHandler.RaiseCallbackEvent(string eventArg) { String[] a = new String[31]; a[1] = "Anna"; a[2] = "Brittany"; a[3] = "Cinderella"; a[4] = "Diana"; a[5] = "Eva"; a[6] = "Fiona"; a[7] = "Gunda"; a[8] = "Hege"; a[9] = "Inga"; a[10] = "Johanna"; a[11] = "Kitty"; a[12] = "Linda"; a[13] = "Nina"; a[14] = "Ophelia"; a[15] = "Petunia"; a[16] = "Amanda"; a[17] = "Raquel"; a[18] = "Cindy"; a[19] = "Doris"; a[20] = "Eve"; a[21] = "Evita"; a[22] = "Sunniva"; a[23] = "Tove"; a[24] = "Unni"; a[25] = "Violet"; a[26] = "Liza"; a[27] = "Elizabeth"; a[28] = "Ellen"; a[29] = "Wenche"; a[30] = "Vicky"; Int32 i; if (eventArg.Length > 0) { for (i = 1; i < 31; i++) { String suggestion = a[i].Substring(0, eventArg.Length).ToUpper(); if (eventArg.ToUpper() == suggestion) { if (hint == "") hint = a[i]; else hint = hint + " , " + a[i]; } }//'Output "no suggestion" if no hint were found // 'or output the correct values if (hint == "") hint = "no suggestion"; } else hint = "no suggestion"; } //Return a string that will be received and processed // by the clientCallback JavaScript funtion String ICallbackEventHandler.GetCallbackResult() { return hint; } }
Client Side Code:
<script language=javascript>
function GetHint()
{
  var message = document.form1.tFirstName.value;
  var context = '';
  <%=getHintFromServer%>
}
         
function ShowHint(hint) {
  var spanHint=document.getElementById("txtHint");
  spanHint.innerHTML=timeMessage;
}
</script>

Drawbacks of Using Script Callbacks

Using ASP.NET Script callbacks has a few issues:

1. Cross-browser Support

ASP.NET Script callbacks will work with Internet Explorer, Firefox and other Mozilla-compliant browsers. It ensures each compliant browser can call the server and return with server-side response, however not all browsers supports dynamic partial page updates. Even with those that do, it is important that script code strictly follows the W3C DOM (Document Object Model - DOM) standards.

In the above example, to update the text inside the span tag called txtHint, instead of directly calling txtHint.innerHTML or using document.all.txtHint: We use the document.getElementById method to retrieve the element then update its content:

var spanHint=document.getElementById("txtHint");
spanHint.innerHTML=...;

2. Server's Response Delivery Format

With each script's callback, the server responds with a string. This works very well with small amount of data. However, it gets problematic with large complex data types. It defeats the purpose if we have to rely on the client-side script on laborious and intensive data parsing, let alone doing so is error-prone.

3. Problem with multiple callbacks

ASP.NET script callback works fine with a single call generated from a single control. However, it gets messy if multiple controls issue multiple callbacks. Because no matter where and how the call is generated, it all gets to be handled by the RaiseCallbackEvent method on the server side. To differentiate the calls and their senders, there is only one way, which is to bundle all necessary information into a string and pass that to the GetCallbackEventReference method, which in turn will be passed to the RaiseCallbackEvent method. It is also possible to write a custom class to handle multiple callbacks.

For more details, please see Script Callbacks in ASP.NET 2.0 - interesting, but lacking.

AJAX

The bundle of technologies (DHTML, JavaScript, XmlHTTPRequest, CSS) that is now coded as AJAX (Asynchronous JavaScript And XML) has been around for a long time. However, only after the launch of a string of successful Google applications (such as Google Maps, Google Suggest, and Gmail) it gained enormous and lasting popularity.

In its bare bone, AJAX makes direct calls to server using the JavaScript XMLHttpRequest object. The XMLHttpRequest object has a readyState property with 5 possible values, a value of 4 indicates a call to server is complete and the calling party can update part of the page based on the response sent back from the server.

ASP.NET AJAX

The raw infrastructure and logic of AJAX is very simple. However, using AJAX in its raw form to write truly interactive and appealing web pages demands extensive skills in JavaScript and sidestepping the various traps caused by the subtle differences between various browsers. It also entails that programmers reinvent the wheel, repeatedly rewriting the same code to recreate the same behavior for common controls. Therefore, many AJAX frameworks have sprung up to free programmers from toiling around sending request and processing responses at its lowest level. Many frameworks also provide a set of sophisticated tools and protocols. ASP.NET AJAX (formerly known as ATLAS) is such a comprehensive yet still fast evolving framework designed for ASP.NET.

An ASP.NET AJAX application can be both server-centric or client centric. In a server-centric application, partial page updates are administrated by a server control called UpdatePanel. It behaves as a intermediate broker between the requesting and responding party, as shown in the following diagram:

For a regular ASP.NET server page to realize partial page-update, the easiest way is to place one or more parts of web page inside an UpdatePanel. A web page can have multiple UpdatePanel controls, an UpdatePanel can also have nested UpdatePanel controls. It is also allowed to have controls outside of an UpdatePanel defined as triggers to fire a partial update.

While it is possible for the UpdatePanel control to work with client script, the functionalities are rather limited - such as stopping and canceling asynchronous postbacks, custom error-message handling, etc. And you must call a reference to the PageRequestManager class in the Microsoft AJAX library. It is more common to use the AJAX library to create custom client components to enable client behaviors, and then use these components as server controls' extensions. The host of components provided by the ASP.NET AJAX Control Toolkit is such custom client components.

In a client-centric AJAX application, a JavaScript function directly calls a Webservice through a script proxy class. Again a new set of rules must be strictly followed. First for a webservice to be consumed by a client-side script, it must be marked with the ScriptService attribute. In the calling page, a reference to the Webservice must be placed inside a ScriptManager control and specify its path to the Webservice, as in the following code:

<asp:ScriptManager runat="server" ID="scriptManager">
  <Services>
    <asp:ServiceReference path="MyWebService.asmx" />
  </Services>
</asp:ScriptManager>

It is also possible to for a JavaScript to call a static page method that is marked with the [WebMethod] keyword.

Summary:

To enable the communication between server and client, more importantly, to enable partial page rendering, ASP.NET has two major approaches: one is script callbacks, the other ASP.NET AJAX. While script callbacks represents an earlier primitive approach which leaves much to be desired, ASP.NET AJAX represents a sophisticated framework that includes server and client-side components, a JavaScript library (AJAX library), and a collection of server-side classes and methods (AJAX extensions).

While ASP.NET AJAX has enjoyed a lot of exposure and gained lasting popularity and influence, script callbacks are much less well-known. However, given that script callbacks are extensively used by such ASP.NET controls as the TreeView and GridView, its approach still merits some exploration. Therefore this article showed the details of the usage of script callbacks, examining some of its downsides, and briefly introduces the underlying logic of AJAX, and the programming models of ASP.NET AJAX in particular.

References

JavaScript with ASP.NET 2.0 Pages - Part 1
ASP.NET AJAX documentation
Cutting Edge: Perspectives on ASP.NET AJAX
Cutting Edge: Implications of Script Callbacks in ASP.NET
Script Callbacks in ASP.NET 2.0 - interesting, but lacking

About Xun Ding

Web developer, Data Analyst, GIS Programmer

View complete profile

Top Articles in this category

JavaScript with ASP.NET 2.0 Pages - Part 1
ASP.NET 2.0 has made quite a few enhancements over ASP.NET 1.x in terms of handling common client-side tasks. It has also created new classes, properties and method of working with JavaScript code. This article explores the enhancements and the various ways of injecting JavaScript programmatically into ASP.NET 2.0 pages.

ASP.NET ComboBox
The ASP.NET ComboBox is an attempt to try and enhance some of the features of the Normal ASP.NET DropDownList.

Upload multiple files using the HtmlInputFile control
In this article, Haissam Abdul Malak will explain how to upload multiple files using several file upload controls. This article will demonstrates how to create a webform with three HtmlInputFile controls which will allow the user to upload three files at a time.

Using WebParts in ASP.Net 2.0
This article describes various aspects of using webparts in asp.net 2.0.

An Architectural View of the ASP.NET MVC Framework
Dino Esposito introduces the ASP.NET MVC framework.

Top
 
 
 

Discussion


Subject Author Date
placeholder Microsoft JScript runtime error: Object expected byrdz eye 9/11/2007 8:37 AM
RE: Microsoft JScript runtime error: Object expected Xun Ding 9/11/2007 11:14 AM
placeholder txtHint not populated Vadim Z 4/20/2007 10:46 AM
Thanks, I got past the JScript errors but... byrdz eye 9/17/2007 8:23 AM
placeholder RE: The code - second try byrdz eye 9/17/2007 8:27 AM
RE: RE: The code - second try Xun Ding 9/17/2007 11:18 AM
placeholder Re: txtHint not populated Sonu Kapoor 4/20/2007 10:48 AM

Please login to rate or to leave a comment.

Product Spotlight