Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
30 Sep 2011 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here