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>
Advertisements
Tagged with:
Posted in General

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow me
   RSS Feed    Twitter    Linked In

Write you email address to subscribe at this blog and to receive new posts by mail.

Join 567 other followers

Who I am?






%d bloggers like this: