Blog of Denis VOITURON

for a better .NET world

Implementing ICallbackEventHandler

Posted on 2013-02-06


With HTML5, many web development will use WebSockets or AJAX communications. These technics are very useful when you use ASP MVC or other similar language. But if you want to develop with ASP.NET, Microsoft give us a similar technology to raise a server event by a web client action. To do that, you must implement System.Web.UI.ICallbackEventHandler.

How it works?

When you implement ICallbackEventHandler, you must write two methods fired by ASP.NET:

The web client can send data without post all page (like Ajax) and call these two methods RaiseCallbackEvent, and next GetCallbackResult on the server page. But firstly, you must register the a “Callback Reference” to define two similar JavaScript function (to send data to the server and to receive data from the server).


Code example

protected override void OnLoad(EventArgs e)

   Control control = Page;
   string functionToSendData = "SendToServer";      // See HTML code below
   string functionReceived = "ReceiveFromServer";   // See HTML code below

   // Registering of JavaScript functions: SendToServer and ReceiveFromServer.
   if (!Page.ClientScript.IsClientScriptBlockRegistered(functionToSendData))
      string callbackReference = Page.ClientScript.GetCallbackEventReference(control, "arg", functionReceived, "context", true);
      string callbackScript = "function " + functionToSendData + "(arg, context) { " + callbackReference + "; }";
      Page.ClientScript.RegisterClientScriptBlock(control.GetType(), functionToSendData, callbackScript, true);

// First method raised by the Web Client.
public void RaiseCallbackEvent(string eventArgument)
   _eventArgument = eventArgument;

// Second method raised by the Web Client.
public string GetCallbackResult()
   return String.Format("{0} at {1:HH:mm:ss}", _eventArgument, DateTime.Now);
<script type="text/javascript">
    function ReceiveFromServer(arg, context) {
        alert(arg + ' on ' + context);
  <div onclick="SendToServer('Yes... clicked', 'MyContext');">Click me</div>



Follow me

Recent posts