Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Exploring Client Callback

, 19 Dec 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Client Callback is one of the very important features provided by ASP.NET. Earlier I was not aware on this. In my last application, I implemented this and got a very good result. This is another way to avoid full post back on the page and can be a great alternative of the Ajax update panel. Also [..

Client Callback is one of the very important features provided by ASP.NET. Earlier I was not aware of this. In my last application, I implemented this and got a very good result.

This is another way to avoid full post back on the page and can be a great alternative to the Ajax update panel.

Also I was looking for a good article but could not find one, explaining the details. So I thought of sharing with you all.

There are various ways, update a part of page without a full page post back, like update panel, callback, etc. But I found callback is a very useful approach certain times. When we used to display the data.

So here, in this article, I will be discussing the Client Callback, how to implement this, their pros and cons, and how it is handled by ASP.NET.

What is Client Callback

We can define the Client Callback like this “Client Callback provides us a way to call a server side code/method asynchronously and fetch some new data without page refresh.”

So one can initiate Client callback from JavaScript and get the result that can be shown on UI after any required modification. Let's take a pictorial overview.

How to implement Client Callback: To implement callback, one needs to follow the below steps:

Things required at Server Side:

  1. Implement interface ICallbackEventHandler on any page or control where implemented.
  2. Need to implement two methods RaiseCallbackEvent and GetCallbackResult provided by the interface ICallbackEventHandler.
  3. RaiseCallbackEvent event is called to perform the Callback on server.
  4. GetCallbackResult event returns the result of the callback.
    (Note: There is a property IsCallback of page returns true, if callback is in progress at server.)

Things required at Client Side:

Apart from the above steps, we also require a few client scripts to complete the Callback functionality. These are:

  1. A function that is registered from server and called by any function that wants to initiate the callback. It also takes one argument, that can be passed to server.
  2. Another function, that is called after finishing the callback, which returns the callback result.
  3. One more helper function that performs the actual request to the server. This function is generated automatically by ASP.NET when you generate a reference to this function by using the GetCallbackEventReference method in server code.

Lots more things have been written, now let's jump to the code.

Here in my example: I have a button and a textbox which is taking Sex type. And on clicking of this button, I am initiating the callback and sending the type as an argument and accordingly creating the result and sending it back to the client. And at client side, I am displaying in a Client side Div.

So this is a demo, for how to use callback.

Server side code:

I have taken a global variable string that is used to hold the response, sent to the client as:

string result;

and:

public void RaiseCallbackEvent(String eventArgument)
 {
 if (eventArgument == "M")
 {
 result = "You are Male";
 }
 else if (eventArgument == "F")
 {
 result = "You are Female";
 }
 else
 {
 result = "Cannot say";
 }
 } 

The above method is called at server side, which has one argument, that is passed from the Client. It takes here the textbox value and returns the result accordingly.

Another Server side method that is called is:

public string GetCallbackResult()
 {
 return result;
 }

It just returned the result that is generated by the method RaiseCallbackEvent.

Also, we need to register some Client side script at Page load.

Here, we need to create a Callback reference, that is the Client side method that is called, after finishing the callback, and assign that reference in the method that initiates callback from Client.

Let's see the code:

protected void Page_Load(object sender, EventArgs e)
 {
 //Creating a reference of Client side Method, that is called after callback on server
 String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg",
 "ReceiveServerData", "");

 //Putting the reference in the method that will initiate Callback
 String callbackScript = "function CallServer(arg, context) {" +
 cbReference + "; }";

 //Registering the method
 Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
 "CallServer", callbackScript, true);
 }

We should also write one line at pageload, because no code is required to be executed when call back is in progress:

if (Page.IsCallback)
 return;
Client Side (aspx) code:

There are two JavaScript functions. The first is called to initiate the callback, and other one is called after finishing server side callback events to update the UI.

Let’s see the first one:

function InitiateCallBack() {
 // gets the input from input box
 var type = document.getElementById('txtType').value;
 //Initiate the callback
 CallServer(type,'');
 }

It is called from when user clicks on button. Now let’s move to the other function:

// Called after the server side processing is done
 function ReceiveServerData(arg, context) {
 //arg: hold the result
 //Updating the UI
 document.getElementById('divCallbacl').innerHTML = arg;
 }

And my aspx code is like this:

<div>
 <span>Enter your Sex(M/F):</span>
 <input id="txtType" type="text" />
 <input id="Button1" type="button" value="button" onclick="InitiateCallBack();"/>
 <div id="divCallbacl">
 </div>

The above are self explanatory.

ClientCallback: Digging Deep

As I said, it gives faster response, it actually trims down the page life cycle. Many of the events do not execute. We’ll see it. Also to distinguish, at server side, whether it is a normal postback or a Callback. One will find the property isCallback true, which shows that it is a callback request, which I have suggested to use at Pageload earlier. Also the IsPostBack property will also be true.

One more thing, viewstate information is retrieved and available at server but any changes made in it do not persist. As we’ll see the Callback lifecycle Saveviewstate event doesn’t fire. Which also leads to better performance.

Now let's see the lifecycle comparison between normal postback and a Callback.

As we can see above, SaveViewstate and render events do not get fired on server. So it does two things, one we get better performance and on the flip side, we cannot save viewstate so we should keep in mind while implementing this.

Where to use, where not to

  • Callback is light action and gives us better performance over normal Update Panels.
  • One should use Client Callback, for display purposes only. Because we would not get the updated/entered data from the UI on server.
  • Also viewstate does not get maintained across during Postback. So one should not rely on it.

License

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

Share

About the Author

Brij
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.
 
He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.
 
He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.
 
He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.
 
Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Brij's arena of .NET
 
Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008
Follow on   Twitter

Comments and Discussions

 
QuestionIt's a nice shot! PinmemberBinhNhi098-Feb-12 13:23 
AnswerRe: It's a nice shot! PinmentorBrij9-Feb-12 5:22 
Thanks a lot
Cheers!!
Brij
Microsoft MVP ASP.NET/IIS
Visit my Blog: http://brijbhushan.net

GeneralMy vote of 5 PinmemberAnurag Gandhi8-Sep-11 0:05 
GeneralRe: My vote of 5 PinmentorBrij9-Feb-12 5:23 
GeneralMy vote of 5 PinmemberDilip Baboo10-Mar-11 11:30 
GeneralRe: My vote of 5 PinmvpBrij11-Mar-11 18:58 
GeneralMy vote of 5 Pinmvpthatraja9-Jan-11 15:57 
GeneralRe: My vote of 5 PinmvpBrij10-Jan-11 4:19 
Generali like it PinmemberPranay Rana30-Dec-10 23:53 
GeneralRe: i like it PinmvpBrij10-Jan-11 4:18 
GeneralMy vote of 5 PinmvpAbhijit Jana20-Dec-10 6:12 
GeneralRe: My vote of 5 PinmentorBrij20-Dec-10 7:05 
GeneralMy vote of 5 PinmemberSudeep35019-Dec-10 19:50 
GeneralRe: My vote of 5 PinmentorBrij20-Dec-10 7:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141220.1 | Last Updated 19 Dec 2010
Article Copyright 2010 by Brij
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid