Wednesday, October 15, 2008

Script Callback in ASP.NET

In very simple term script callback is a machanims of calling server side code from client side(using javascript) without rendering the web page. In other term posting web page asynchronously. In the heart of it, is XmlHttpRequest DOM object. During a normal page postback(synchronous), the Web page and controls are recreated and a new version of the entire Web page is rendered on the client. Where as in the client callback browser create new connection using XmlHttpRequest to send only the callback data to the remote server not the content of entire page making the page lifecycle short(page rendering event does not occur).

The ASP.NET 2.0 implementation of client callbacks uses the Client Callback Manager. After initial page load, subsequent requests to server-side code are made by a client-side component, without refreshing the entire Web page. The page runs a modified version of its normal life cycle where the page is initiated and loaded, but the page contents are not rendered. Instead, a special method in the server-side code is invoked, which processes the callback request content, then returns a value to the browser that can be read by JavaScript function. The JavaScript function uses technology inherent to the browser (e.g. DOM, DHTML) to update Web page content dynamically. The Web page continues to stay live while the request is being processed.

The Page.IsPostback property will return true for both request types(normal postback & client callback). The Page. But IsCallback property will return true only when the request is a client callback.

Page LifeCycle in case of Client Callback:

Init-> LoadState-> ProcessPostbackData-> Load-> ChangeEvent-> RaiseCallbackEvent-> GetCallbackResult -> Unload

Note-: PostBack , PreRender, Render and SaveState events are skiped.

Implementing Client Callback:

Following are the steps:-

1. Write a javascript function that will request the callback by calling WebForm_DoCallback function.

2. Write another javascript function(Callbackhandler) that will receive the callback and do the needful client side processing.

3. Call the GetCallbackEventReference method in the Page_Load event.

This method creates a JavaScript string containing code for calling WebForm_DoCallback function in the client Web page to start the callback.

like :WebForm_DoCallback('__Page', message, processMyResult, context, postMyError, true)

Syntax: GetCallbackEventReference(control, argument, clientCallback, context, clientErrorCallback, useAsync);

control - The control or the page which implements ICallbackEventHandler.
argument - data that needs to be processed by the asynchronous call.
clientCallback - javascript function(Callbackhandler) that will receive the result.
context - Name of a client-side JavaScript variable. Usually used to determine the content of the message (argument) in the callback request. The value of the variable will be stored on the client as the context parameter associated with a callback.
clientErrorCallback - javascript function that will receive the result when server throws an error.
useAsync - boolean value to determine if the call is async or not.

4. Implement the System.Web.UI.ICallbackEventHandler interface by defining its 2 methods- RaiseCallbackEvent and GetCallbackResult.

Here is the code sample:

File - syncCallback.aspx

< script language="javascript">
function CallbackHandler(result, context) //Step 2
{
alert(result);
}
< /script >

< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server" >
< title >Client Callback Demo< /title >
< /head >
< body >
< form id="form1" runat="server" >
< div >
Name :< input id="txtName" type="text" />
< input id="btnClient" type="button" value="Asyn Callback" runat="server" / >
< /div >
< /form >
< /body >
< /html >


File - syncCallback.aspx.cs

public partial class syncCallback : System.Web.UI.Page, ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
string CallbackRef = ClientScript.GetCallbackEventReference(this,"document.all['txtName'].value","CallbackHandler", "null",true);
//Step 3 will generate following string

// WebForm_DoCallback('__Page',document.all['txtName'].value,CallbackHandler,null,null,true)


btnClient.Attributes["onclick"] = String.Format("javascript:{0}",CallbackRef); //Step 1
}

#region ICallbackEventHandler Members
string _str;

public string GetCallbackResult() //Step 4
{
return _str;
}

public void RaiseCallbackEvent(string eventArgument) //Step 4
{
_str = "Hello " + eventArgument;
}

#endregion
}

2 comments:

Anonymous said...

it was really helpful for beginner.
thanx
i was looking for this for a long time

Ten said...

Hi i have a web server control with the webform_docall back which works on my dev system, but doesnt work when deployed to my domain