Learn ASP.NET Web Forms and ASP.NET MVC. Intensive courses for professional developers. Conducted by Bipin Joshi in Thane. Read more details here.

Client Callbacks in ASP.NET 2.0

Introduction

Over the last few weeks I have been writing about AJAX and ASP.NET (Part 1, Part 2, Part 3 and Part 4). AJAX model reduces server post backs using client script and XMLHTTP. Now that ASP.NET 2.0 is released, let's see what it has to offer to do the same thing. ASP.NET 2.0 allows you to execute server side code from your client browser via a feature called as "Client Callback". In this article I will explain what Client Callbacks are and how to program them in your web forms.

What are Client Callbacks?

The default page processing model in ASP.NET is post back oriented. That means when you click a post back causing control (such as button) your form gets submitted back to the server. Server side events are raised and the entire page output is sent back to the client. This can cause significant network overhead. The Client Callback feature allows you execute code from a web form without posting the form back to the server. You just retrieve the required value and update a small part of the overall UI. This way you save the amount of data passed over the network. It also improves the user experience because of quicker response time.

Classes and JavaScript functions involved

The main used while working with client callbacks is ClientScriptManager. This class is used to manage client side script emitted by your page. The Page.ClientScript property returns an instance of this class for you which is attached to the current web form by ASP.NET framework.

In a typical usage you are required to write three JavaScript functions to implement client callbacks:

  • One that calls the server (CallServer in the example below)
  • One that calls the above function when you click on a post back causing control (SendCustomerID in the example below)
  • One that receives the data returned when the call is over (ReceiveServerData in the example below)

As an example we will develop a web form with a DropDownList and a ListBox. The DropDownList is filled with CustomerIDs from Customers table of Northwind database. The ListBox displays the OrderIDs for a selected customer.

Registering the client side functions with the page framework

In order to register the above functions with the page framework you need to write the following code in the Page_Load event:

ClientScriptManager m = Page.ClientScript;
string str = m.GetCallbackEventReference
(this, "args", "ReceiveServerData", 
"'this is context from server'");
string strCallback = "function CallServer(args,context)
{" + str + ";alert(context);}";
Page.ClientScript.RegisterClientScriptBlock
(this.GetType(), "CallServer", strCallback, true);

Here,

  • We got the reference of ClientScriptManager instance associated with the current page using Page.ClientScript property
  • We then called GetCallbackEventReference method. This method generates the required markup to call the server from the client. You need to pass name of the client function parameter that acts as arguments, Name of the client function that receives the server data and a context string.
  • The GetCallbackEventReference function returns the required script as a string. You need to wrap this string in a client side function (CallServer in above example).
  • Finally you need to emit this function using RegisterClientScriptBlock method

You also need to write a client side function that actually calls the CallServer function when user changes CustomerID from the DropDownList. You do this using Attributes collection.

DropDownList1.Attributes.Add("onchange",
 "return SendCustomerID();");

Here, we attach a client side function called SendCustomerID to the client side OnChange event of the DropDownList.

Implementing ICallbackEventHandler interface

In addition to registering the client side functions, you also need to implement an interface called ICallbackEventHandler on your web form class. This interface contains two methods - RaiseCallbackEvent and GetCallbackResult. The former gets called when the client calls the server and the later is called when the server returns the data back to the client. The following code illustrates how these functions can be used.

public partial class _Default : 
System.Web.UI.Page,ICallbackEventHandler
{
public string GetCallbackResult()
{
 return str;
}

public void RaiseCallbackEvent(string eventArgument)
{
SqlDataAdapter da = new SqlDataAdapter
("select orderid from orders where customerid='" 
+ eventArgument + "'", 
@"data source=.\sqlexpress;initial catalog=northwind;
integrated security=True");
DataSet ds=new DataSet();
da.Fill(ds);
str=ds.GetXml();
}

In the RaiseCallbackEvent method we simply filled a DataSet with records matching the selected CustomerID and assign the XML representation of it to a string variable str. This variable is returned to the client in the GetCallbackResult method.

Client Side Functions

The client side functions that you need to write are shown below:

function SendCustomerID()
{
var id=document.getElementById("DropDownList1").value;
CallServer(id,"This is context from client");
return false;
}

function ReceiveServerData(args, context)
{
alert(context);
var obj = new ActiveXObject("MsXml2.DOMDocument");
obj.loadXML(args);
var dsRoot=obj.documentElement; 
var ddlOrders = document.getElementById("ListBox1");
for (var count = ddlOrders.options.length-1; 
count >-1; count--)
{
ddlOrders.options[count] = null;
}
var orders = dsRoot.getElementsByTagName('orderid');
var text; 
var listItem;
for (var count = 0; count < orders.length; count++)
{
text = (orders[count].textContent || 
orders[count].innerText || orders[count].text);
listItem = new Option(text, text, false, false);
ddlOrders.options[ddlOrders.length] = listItem;
}
}

In the SendCustomerID function we get the selected CustomerID and invoke the CallServer function with it.

In the ReceiveServerData function we receive the XML representation of DataSet (that we returned from GetCallbackResult method. We then populate the ListBox from that data.

Download

The complete source code of the above example is available for download. Please click on the Download Source Code button at the top of this article.

Summary

ASP.NET 2.0 client callback feature allows you to call server side code without making any post back. This reduces the network traffic and results in a quicker response time.

 


Bipin Joshi is the founder of BinaryIntellect Consulting and conducts professional training programs on ASP.NET in Thane. He is a published author and has authored or co-authored books for Apress and Wrox press. To know more about him click here. To know more about his training programs go here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Associated Links
Download Source Code

Tags : ASP.NET AJAX Web Forms JavaScript
Posted On : 20 Nov 2005
Current Rating :
Rate this article :


This page is protected by copyright laws. Copying in any form is strictly prohibited. For Copyright notice and legal terms of use click here.

Protected by Copyscape