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






4.69/5 (24 votes)
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:- Using
PageMethods
- Implementing
ICallbackEventHandler
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.
<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, addSystem.Web.UI.ICallbackEventHandler
to the page class like this:
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
:
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
:
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:
<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:
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.
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.
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.
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
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
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 bothPageMethods
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
.