Click here to Skip to main content
15,867,330 members
Articles / Web Development / ASP.NET
Tip/Trick

How to: Implement ICallBackEventHandler (calling server side code from client side)

Rate me:
Please Sign up or sign in to vote.
4.69/5 (24 votes)
30 Sep 2011CPOL4 min read 67K   29   20
An easy guide on how to implement ICallbackEventHandler

Introduction


This aims to simplify and make the implementation of ICallbackEventHandler easy to follow and understand.

Background


While I was looking for a way to call a server side code or function from client side script, I came across two methods:

  1. Using PageMethods
  2. Implementing ICallbackEventHandler

However, I did not find an easy article to understand how to implement ICallbackEventHandler. Therefore, I write this article to make it easier for others to understand.

Using the Code


Part1: Preparing the Page


Prepare your .aspx page; have a button to call the server on click and a label to display the result. 


ASP.NET
<body>    
    <form id="form1" runat="server">
    <div>
		<input id="Button1" type="button" value="Call Server" onclick="CallServer(1, alert('Calling Server Now'));" />
		<br/>
		<label id="lbl">Label State Before Calling the Server</label>
    </div>
    </form>
</body>

Part2: Implementing the Interface


First, add System.Web.UI.ICallbackEventHandler to the page class like this:
C#
public partial class Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
}

Then, you will have to implement the two functions RaiseCallbackEvent and GetCallbackResult which are part of the ICallbackEventHandler.

RaiseCallbackEvent: This is the actual event that will be called by the client side script, so here you put what you want your server to do. To simplify, the button's onclick event, triggers "CallServer" method (refer to the HTML above) which calls RaiseCallbackEvent.


Here is simple implementation of RaiseCallbackEvent


C#
public void RaiseCallbackEvent(string eventArgument)
{
            //This method will be called by the Client; Do your business logic here
            //The parameter "eventArgument" is actually the paramenter "arg" of CallServer(arg, context)

            //tempVar is a local string variable
            tempVar = eventArgument;
}

After RaiseCallbackResult finishes processing your code, the GetCallbackResult is called.

GetCallbackResult: returns something back to the client. It usually returns results of your processed code in RaiseCallbackEvent. But, you can return anything else you want. The returned result is handled by a javascript function. (in our case it will be HandleResult; we will implement it later).


Here is an implementation of GetCallbackResult:


C#
public string GetCallbackResult()
{
            //This is called after RaiseCallbackEvent and then sent to the client which is the
            //function "HandleResult" in javascript of the page
            
            return "Calling server was successful.<br/>The passed argument was " + tempVar;
}

Part3: Implementing the javascript function (HandleResult)


HandleResult will recieve the results from GetCallbackResult for further processing.

This is easy to implement: 


ASP.NET
<head runat="server">
    <title>Implementing ICallbackEventHandler</title>

	<script type="text/javascript">
		
		//the parameter arg is what is returned from GetCallbackResult
		function HandleResult(arg, context) {
			lbl.innerHTML = arg;
		}

	</script>
</head>

Part4: Linking the Server Side code to the Client Side Script


This is the hardest part to understand.  To make it easier for you, first I will post the code then i will explain what each statement do.

The code:


C#
protected void Page_Load(object sender, EventArgs e)
        {

            //Get the Page's ClientScript and assign it to a ClientScriptManger
            ClientScriptManager cm = Page.ClientScript;

            //Generate the callback reference
            string cbReference = cm.GetCallbackEventReference(this, "arg", "HandleResult", "");

            //Build the callback script block
            string cbScript = "function CallServer(arg, context){" + cbReference + ";}";

            //Register the block
            cm.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);

        }


NOTE: Before we begin, remember that this block of code is what links the client to the server. It can be called from any other page within the website where you only need to do is to substitute the first attribute of GetCallbackEventReference and second attribute of RegisterClientScriptBlock with appropriate substitutions. (But for the sake of simplicity we will use this and this.GetType() respectivly.)

Now take time to focus and understand:

Step1: Get the Page's ClientScript and then assign it to ClientScriptManager Object. 


C#
ClientScriptManager cm = Page.ClientScript;

ClientScriptManager has the key role here. It generates the callback Reference (cbReference) which is used to build the callback Script block (cbScript). And finally register the block to create the link between the Server Side code and Client Side script.

Step2: Generate the callback Reference.


C#
string cbReference = cm.GetCallbackEventReference(this, "arg", "HandleResult", "");

As you see here we use the ClientScriptManager(cm) to generate the callback Reference (cbReference).  cbReference holds the script code on how to call the server from the client. (You don't need to know what it holds and its details, all you need to know is how to generate it). The second parameter is the argument name of CallServer which is the javascript function that calls the GetCallbackResult. The fourth parameter replaces context parameter of HandleRequest, for our simplicity we leave it empty, but you can experiment with it by placing it with "alert('Call Server Done!')".

Step3: Build up the script block.


C#
string cbScript = "function CallServer(arg, context){" + cbReference + ";}";

cbScript is the script block that you will use to register with cm. CallServer is the function that initiates the call to the server (i.e. it will call RaiseCallbackEvent) and the parameter arg in CallServer is the same parameter eventArgument in RaiseCallbackEvent. 

Step4: Register the script block cbScript with the ClientScriptManager cm


C#
cm.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);

The fourth parameter is a boolean for whether you want to generate script tags. For simplicity you choose true. 

Summary 


The flow of how the events fires up:


  • CallServer
  • RaiseCallbackEvent
  • GetCallbackResult
  • HandleResult

or

Client (intiates the call) -> Server (process information, generate results and send it back to client) -> Client (Handle results)


However you still have the option to choose this flow:


Client -> Server


For that just leave GetCallbackResult and HandleResult unimplemented.


Points of Interest


I tried both PageMethods and ICallbackEventHandler. With PageMethods you can only have static functions to be called by the client, which did not help me when i wanted to play with Application and Session variables. So, then I tried ICallbackEventHandler and I was pretty much satisfied that I could manipulate Application and Session variables and on top of that I can pass data from client to server, have it processed and be sent back to the client.

So, if you just want to get a simple call to a server code use PageMethods. On the other hand, if you wanted to pass data to the server from the client OR want to manipulate Application or Session variable then use ICallbackEventHandler.


Notes of Updates


October 1, 2011(v4):


- Added a note in Part4 to clarify some misunderstandings


- I mistakenly wrote at part4 step2 that the 2nd argument of GetCallbackEventReference is the argument name for HandleRequest javascript function where the correct thing is that the second argument of GetCallbackEventReference is the argument name of CallServer javascript function.


-Added an explanation of the fourth parameter of GetCallbackEventReference.

License

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


Written By
Bahrain Bahrain
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Question"how to insert data in sql table using Json and icallback eventhandler" Pin
Sreeraam_d18-Dec-12 19:20
Sreeraam_d18-Dec-12 19:20 
QuestionMy vote of 5 Pin
Member 361173631-Jul-12 2:20
Member 361173631-Jul-12 2:20 
AnswerRe: My vote of 5 Pin
Jassim Makki7-May-13 8:01
Jassim Makki7-May-13 8:01 
GeneralRe: Thanks for your remarks, I have updated the Tip/Trick to cla... Pin
Jassim Makki30-Sep-11 14:38
Jassim Makki30-Sep-11 14:38 
GeneralRe: Since it is not straight forward, a bit more detailed explan... Pin
Shahare30-Sep-11 5:43
Shahare30-Sep-11 5:43 
GeneralUseful, Thanks for sharing Pin
Sridhar Patnayak3-Feb-12 6:14
professionalSridhar Patnayak3-Feb-12 6:14 
GeneralReason for my vote of 5 I have been using Pagemethods for 5m... Pin
Jagz W21-Nov-11 16:28
professionalJagz W21-Nov-11 16:28 
GeneralRe: And you are welcome :) Pin
Jassim Makki15-Jan-12 8:42
Jassim Makki15-Jan-12 8:42 
And you are welcome Smile | :)
GeneralReason for my vote of 4 The explanation was a bit missing on... Pin
Shahare26-Sep-11 20:14
Shahare26-Sep-11 20:14 
GeneralRe: Thanks for voting, can you please tell me what do you think ... Pin
Jassim Makki29-Sep-11 21:00
Jassim Makki29-Sep-11 21:00 
GeneralNicely done (Y) Pin
Secrets20-Sep-11 21:25
Secrets20-Sep-11 21:25 
GeneralRe: Thanks!! Pin
Jassim Makki29-Sep-11 21:01
Jassim Makki29-Sep-11 21:01 
GeneralReason for my vote of 5 Thanks, never used this before but v... Pin
BrianBissell20-Sep-11 2:55
BrianBissell20-Sep-11 2:55 
GeneralRe: you welcome :) Pin
Jassim Makki29-Sep-11 21:02
Jassim Makki29-Sep-11 21:02 
GeneralVery nice work. Voted 5. Pin
M.Hussain.20-Sep-11 2:09
M.Hussain.20-Sep-11 2:09 
GeneralRe: Thanks!! Pin
Jassim Makki29-Sep-11 21:02
Jassim Makki29-Sep-11 21:02 
GeneralReason for my vote of 5 simple explanation Pin
itaitai19-Sep-11 22:42
professionalitaitai19-Sep-11 22:42 
GeneralRe: Thanks that is always my aim ;) Pin
Jassim Makki29-Sep-11 21:03
Jassim Makki29-Sep-11 21:03 
GeneralReason for my vote of 5 Very nice. thanks for sharing. Pin
Burak Ozdiken14-Sep-11 11:36
Burak Ozdiken14-Sep-11 11:36 
GeneralRe: You welcome!! Pin
Jassim Makki29-Sep-11 21:03
Jassim Makki29-Sep-11 21:03 

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.