2018-10-23

Implementing ICallbackEventHandler

Introduction

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:

  • RaiseCallbackEvent method received an argument string sent by the web client.
  • GetCallbackResult method send an answer to the web client.

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).

ICallBack

Code example

protected override void OnLoad(EventArgs e)
{
   base.OnLoad(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);
    }
</script>
<form>
  <div onclick="SendToServer('Yes... clicked', 'MyContext');">Click me</div>
</form>

Leave a Reply

Your email address will not be published. Required fields are marked *