Microsoft.NET

……………………………………………….Expertise in .NET Technologies

JavaScript with ASP.NET 2.0 – Part 2

Posted by Ravi Varma Thumati on December 16, 2009

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.

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 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: