Click here to Skip to main content
15,885,652 members
Articles / Web Development / ASP.NET
Article

Client-side callbacks in ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
3.50/5 (15 votes)
9 Dec 2005CPOL9 min read 119.2K   1.5K   56   11
An article on client-side callbacks in ASP.NET 2.0

Contents

  1. Introduction
  2. What does callback mean to me?
  3. What were the earlier technologies?
  4. What is new in ASP.NET 2.0 and how is it different?
  5. The interface
  6. Anatomy of the methods
  7. Example

Introduction

The advent of the internet came up with the help of promising client server technology. The client browser was separated from the server, and it used to make calls at the server, where the server-side script will respond to the call and send back the result to the client. The initial phase was related to the static sites, but with the passage of time, this static world became so dynamic, that now people want to have online versions of so many things. Think of the days, when we had to go to the nearest ATM or bank to find out the balance in our account, or when we had to go to the shop for ordering a text book, or business people making requests to finance, and then the things were crawling on their way.

This powerful model of client server technology changed its face, and now it has become the event driven model; however, under the hood, it is still client server. With .NET, we can very well go ahead and cover the client server model with the event driven model. This all happens transparent to the developer, the viewstate beneath the scene takes care of this.

Now after making it to appear as an event driven model, still there were cracks in the cover and the client server kind of computing was visible through those cracks. Now the callbacks have evolved as a new model to cover these cracks.

What does callback mean to me?

Callbacks are used to improve the client experience, as they can help in avoiding the whole page refresh story of the web. Whenever we are browsing the web, most of the time we will be getting the same page again, but this time it will show us a few more details. Think of the category and subcategory problems. So using callbacks, we can get the data from the server, and the end user will not be able to feel it (or see a boring full page refresh). Moreover, we can also perform server side operations like saving the passed info into a database and then sending a fresh string back to the client which can present the client with an updated view.

What were the earlier technologies?

The callbacks are like the evolving organism, their ancestors are the AJAX kind of animals. Developers have used AJAX to get the same look and feel. However, a callback hides the details of the AJAX from the developer. A developer never writes any code for the XmlHttp object to perform a callback operation.

What is new in ASP.NET 2.0 and how is it different?

The ASP.NET 2.0, when it started coming up with the callback, it started with a new interface, ICallbackEventHandler. However initially, this interface was equipped with only one method, RaiseCallbackEvent. As time passed by, the final flavor of it came with two methods:

  • RaiseCallbackEvent
  • GetCallbackResult

During the initial days, the RaiseCallbackEvent was responsible for doing the processing and then raising the client-side event. Now with the final release, this responsibility has been divided between the above mentioned two methods.

We will only look into the new offers for now.

So the responsibility of the RaiseCallbackEvent is to do the processing and the GetCallbackResult causes the client-side function to be invoked and get called.

When the client initiates a call by doing some action, the server-side RaiseCallbackEvent gets fired and it does the processing. Generally, the result of this processing is made available to one string variable and then this string variable is returned by the GetCallbackResult event which fires after the processing of the RaiseCallbackEvent.

The interface

Here is the full definition of the interface:

C#
namespace System.Web.UI
{    
   public interface ICallbackEventHandler
    {
        // Summary:
        //     Returns the results of a callback event that targets a control.
        //
        // Returns:
        //     The result of the callback.
        string GetCallbackResult();
        //
        // Summary:
        //     Processes a callback event that targets a control.
        //
        // Parameters:
        //   eventArgument:
        //     A string that represents an event
        //     argument to pass to the event handler.
        void RaiseCallbackEvent(string eventArgument);
    }
}

Anatomy of the methods

As whenever we have something less to code, we always have several steps to perform, so that we can use the free infrastructure we are getting due to our less coding effort. If we need to have readymade food, then the steps would be like calling to a hotel/food shop and getting the order processed and get it delivered to us. However the beauty lies in understanding the steps. Without building up a mood to eat a pizza, I can not order my pizza. If I do so, I will land up in spoiling my dinner and mood, both. The same is true for coding callbacks before jumping deep in to it. We need to see what exactly are we trying to do and then how it is going to work for us?

For the callbacks to work for us, we need to have two components to make our call:

  1. The server-side script
  2. The client-side code

Here the server-side script will be a C# class [aspx page] (as we are talking .NET and I am comfortable with C#).

Let us first see the server side steps and then we will see the client side steps.

Server side steps

  1. The server-side control or page (we will refer to it as server side script now onwards) should implement the ICallbackEventHandler.
  2. The server-side script should know which client side function to call, when the processing is finished at the server's end.
  3. Determine the parameters which the server-side script may require, for making the processing decision.
  4. The server-side script must do the plumbing for the client side calls (say, JavaScript functions).

To accomplish the various tasks, the server side scripts use the new functions provided with the framework. One function is used to tell the client-side that the server has finished its working and this is done by making a client-side function call along with the parameters passed. This work is accomplished by the GetCallbackResult method of the page.

We will see more in the code example attached with this article.

Since we are doing these things at the server end, the page load method is a better candidate for doing all this operation.

Client side

  1. There must be a function to start the call, at the server end.
  2. There must be a function which the server will call at the end of its processing. This function in turn will update the client page (step 2 of the server side).

The client side function which starts the call is written at the server side and then we register it using the page class methods. We do so because this function will have the plumbing code for us. This code is generated by .NET so we can use it. This is done using the Page.ClientScript.RegisterClientScriptBlock function.

We will see much in the code example attached with this article.

The example

The example attached with this article will try to get different numbers from the server side without causing the whole page to refresh. For the sake of simplicity, I have omitted various validation checks, like my client is passing some parameter which my server code isn’t expecting.

The sample page which will come as a result, will have a text box and three buttons, and clicking on the first button will bring the text "1, 2 , 3" from the server, and clicking on the second button will bring the text "4, 5, 6", and clicking on the third button will bring "7, 8, 9" from the server.

Server side code and its meaning:

C#
callBackInitiater = 
       Page.ClientScript.GetCallbackEventReference(this, 
       "args", "ServerFeeding","context");

This sets up the client side JavaScript function. ServerFeeding is the name of the function at the client-side which will be called when the method finishes its processing.

So the question is which method on the server side calls the client-side method? The method is actually the RaiseCallbackEvent(string eventArgument); event handler written at the server side. And after this event processing is done at the server side, the server-side script will process the GetCallbackResult() method, which is actually responsible for sending the results back to the client. This pumping of results back to the client is taken care by the framework plumbing which is coming free to us, so we need not bother about it.

C#
string Jsblock = "function callBack(args, context){" + callBackInitiater + "}";

This second line is nothing but, our trying to code the JavaScript function. This function is actually responsible for initiating the call to the server-side script. So here we are placing the callBackInitiater variable's value inside the string we are trying to generate for the client side function. Well, actually, this string will have the plumbing JavaScript code in it as a result of the execution of the Page.ClientScript.GetCallbackEventReference, as the return type of this method is string.

One more point to note is that you can not change the parameter names here: args and context as args and context are coming due to step 1. We can see args and context there too. Well the args argument has got all client-side script arguments passed and context has got the context. We can use the args parameters values in the server side GetCallbackEventReference events processing to do separate actions based on the argument values.

C#
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
                                 "callBack", Jsblock,true);

We are registering the client side script we generated in step two. Please see that the only linking thing is the string “callback”. Please be sure that you are following the case sensitivity as the code we are writing here will be converted in to JavaScript which you can view by doing a right click and View Source on your IE.

Client side code and its meaning:

JavaScript
function ServerFeeding(args,  context)
{
  var s = document.getElementById('Label1');
  s.value = args
}

This method is the method which the server will call once it is done with the processing. See that the name of the method is ServerFeeding which we specified in step 1 of our server side code.

JavaScript
function callServer(args)
{
  callBack (args,"ClientContext");
  return false
}

This method is the initiator of the server side call. Please make note that this method is calling the JavaScript method which we had coded in the server side step 2, and registered in step 3. Here we are passing the client side argument to the server using the args parameter and we have initiated the call to this function using the OnClientClick of the button.

HTML
<asp:Button ID="A" runat="server" 
            Text="Button" OnClientClick = "return callServer(1)"/>
<asp:Button ID="B" runat="server" 
            Text="Button" OnClientClick = "return callServer(2)"/>
<asp:Button ID="C" runat="server" 
            Text="Button" OnClientClick = "return callServer(3)"/>

Please make note of the return statement in the OnClientClick event. This return will cause the posting back of the page as the ASP.NET button renders to be a <input type=submit> in the HTML produced by ASP.NET and the default behavior of the submit button is a post back.

So the above said technique is just a demo of what we can do using the client callbacks of ASP.NET. There are controls in ASP.NET which are now using client callbacks to give a better performance.

Note: the attached example only contains the .aspx and the .cs file. You need to make a Whidbey solution and then add them to the project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
A curious mind.

Comments and Discussions

 
GeneralError Page not implementing interfacemember ICallbackeventhandler Pin
Roopangee Tandon24-May-09 20:28
Roopangee Tandon24-May-09 20:28 
GeneralRe: Error Page not implementing interfacemember ICallbackeventhandler Pin
Amit Kukreti (A)25-May-09 0:01
Amit Kukreti (A)25-May-09 0:01 
GeneralSimple alternative Pin
Member 36788025-Feb-08 11:35
Member 36788025-Feb-08 11:35 
QuestionPostback happens... dunno y? Pin
TheIKnowItAllMan31-Oct-06 3:40
TheIKnowItAllMan31-Oct-06 3:40 
QuestionHow to get the data from control generated by callback method? Pin
getdavid@rediffmail.com12-Jun-06 21:19
getdavid@rediffmail.com12-Jun-06 21:19 
Generalbrowser compatibility Pin
David Allen - Minneapolis12-Dec-05 3:16
David Allen - Minneapolis12-Dec-05 3:16 
GeneralRe: browser compatibility Pin
Paul A. Howes12-Dec-05 4:39
Paul A. Howes12-Dec-05 4:39 
JokeRe: browser compatibility Pin
Sauron-x12-Dec-05 13:15
Sauron-x12-Dec-05 13:15 
AnswerRe: browser compatibility Pin
Amit Kukreti (A)12-Dec-05 17:52
Amit Kukreti (A)12-Dec-05 17:52 
GeneralRe: browser compatibility Pin
Kulderzipke12-Dec-05 21:14
Kulderzipke12-Dec-05 21:14 
GeneralRe: browser compatibility Pin
GaryWoodfine 24-Feb-07 11:28
professionalGaryWoodfine 24-Feb-07 11:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.