Saturday, August 27, 2005

Script Callbacks in ASP.NET

One of the many feature of ASP.NET 2.0 is that it allow us to call to server event from client side with out letting the page to post back and refresh. This mechanism is implemented through callbacks. This feature become very handy when you have very rich UI where refresh and post back become very hectic. For example when we have tree view control on page and we donot want our rich UI page to be post back on every expand or collaps in that scenario one option can be to implement ASP.NET Scripts callbacks. In this way request will be send asynchronously to the server and client will continue to work.

Many implementation has been given for out-of-band patterns i-e calling function from client side to server without letting the whole page to refresh. Few years ago microsoft realeased a interesting technology callled Remote Scripting. It uses some client side scipt to trigger a java language applet which in turns open the sockets to the destination URL. the remote URL must be a classic ASP page that include a call to server side layer of Remote scripting and exposes an object with a given name - public_description. The return value of call must be a string.

Another implementation of out-of-bond pattern is webservice , We know that we can call websevice through java script also. For this we have to use But this behaviour is limit to only Internet Explorer 5.0 and higher version. In this case we use XmlHttp instead of java applet. Now MS tried to solve this problem in 2.0. One good thing of this is, its fully integrated with framework. In ASP.NET 2.0 the scripting model of the page object is enriched with callback abilities that provide ASP.NET specific implementation of a kind of remote scripting.

What ever the implementation is, the pattern of out of bond is same. Which is ,new http channel for sending and getting the response is setup in parallel. the new request should be invisible to the user to avoid any interference with the displayed page. Finally the response you get from this invisible request must be merged with the current page through dynamic changes to the document object model (DOM) of the page.

To use 2.0 script callbacks, you define a trigger element in the page (not a submit button) and bind it to some javascript code. this code will retrieve input data from the current page input fields and prepare a call to a system-provided script function name WebForm_DoCallback in Beta1. This function is expected (in the final release) to open the HTTP connection to the specific remote ASP.NET page. The ASP.NET runtime detects a callback invocation and executes a particular method on the page. The return value of the server-side method is passed back to the client as the response to the previous request. On the client, the response gets passed to a user-defined javascript callback function that can then update the user interface via DHTML. The bottom line is that a round-trip still occures, but the page is not fully refreshed. More importantly, the user can continue working with the controls in the page while the parallel request is served.

Let us now look a small implementation of it.The remote invocation begins by calling a javascript function WebForm_DoCallback , it is built in function. To call a javascript function It is essentail that clickable element not be a submit button. Therefore we cannot render it using asp:button tag because such a server control outputs the submit markup. Therefore we will use normal html button tag.
AS expected the ASP.NET runtime takes care of the request and begin processing it. By looking at the request header, body and viewstate fields it will determine the postback mode. If its figure out that page is being invodked on an out-of-band call , it will set IsCallback property to ture. Next it will figure out the callback mode by looking the _CALLBACK entry in request collection . If such entry exists then runtime conclude that callback invocation is being made. Now runtime checks if the page implements ICallbackEventHandler interface , it invokes the RaiseCallbackEvent method on the interface and prepares the response from the result of the call. A page that implements this interface have following directive
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>
to add function to html button we will add runat server tag to it so that it will be available in code behind.

The remote invocation begins when a call is made to a built-in JavaScript function named WebForm_DoCallback. You don't necessarily need to know the name and signature of this function, as you can get it from a new member of the Page class—the etCallbackEventReference method. So in code behind we will add following

string js = GetCallbackEventReference(this, "document.all['cboEmployees'].value", "UpdateEmployeeViewHandler", "null", "null");btn.Attributes["onclick"] = String.Format("javascript:{0}", js);

actual declaration of docallback is
function WebForm_DoCallback( eventTarget, eventArgument, eventCallback, context, errorCallback) { •••}

In RaiseEventHandler we will write all the code whatever to return to the client. for example

public virtual string RaiseCallbackEvent (string eventArgument)
{ // Get more info about the specified employee
int empID = Convert.ToInt32 (eventArgument);
EmployeesManager empMan = new EmployeesManager();
EmployeeInfo emp = empMan.GetEmployeeDetails (empID);
string[] buf = new string[6];
buf[0] = emp.ID.ToString ();
buf[1] = emp.FirstName;
buf[2] = emp.LastName;
buf[3] = emp.Title;
buf[4] = emp.Country;
buf[5] = emp.Notes;
return String.Join(",", buf);

and in javascript function we will take all back the data and update the UI Component as needed. the return value contain string. This string can actually contain everything you want and need, including XML data or Base64 data, comma-separated values, dates, numbers, and so forth.You can use callbacks to update individual elements of a page , such as a chart or a panel, provide different views of the same data, download additional information on demand, or auto-fill one or more fields, In particular, the ASP.NET2.0 TreeView control uses script callback extensively to implement its expand/collapse features and GridView control uses callbacks to page and sort without explicit postback.


At 9:58 PM, Blogger abhi said...

hi all of you,
i read your document and i got the good idea regarding callback mechanism.



Post a Comment

<< Home