Monday, 11 May 2009

Easy AJAX Callback Using ASP.NET ClientScriptManager

What I am going to show you is a fast, safe, easy way to create an AJAX callback process without manually write any JavaScript code regarding creating and handling XMLHTTPRequest object. The key is to use ASP.NET ClientScriptManager.

I will show you the sever side code first and explain to you what these code will do.

   1:  // Code behind
   2:  protected void Page_Load(object sender, EventArgs e)
   3:  {
   4:      string js = Page.ClientScript.GetCallbackEventReference(
   5:          this, 
   6:          "arg", 
   7:          "ClientCallbackFunction", 
   8:          "ctx", 
   9:          true);
  10:   
  11:      StringBuilder sb = new StringBuilder(); 
  12:      sb.Append("function DoTheCallback(arg, ctx) {"); 
  13:      sb.Append(js); 
  14:      sb.Append("}"); 
  15:      
  16:      Page.ClientScript.RegisterClientScriptBlock(
  17:          this.GetType(), 
  18:          "callbackkey", 
  19:          sb.ToString(), 
  20:          true); 
  21:  }

The first part in the code (line 4 to 9) is creating the JavaScript code which will try to invode ASP.NET AJAX engine, which will maintain a XMLHTTPRequest object for us. In line 7 we specify the callback JavaScript function name is “ClientCallBackFunction”. In line 9 we specify the AJAX calling is asynchronous. In line 6 and 8 we specify the return variable name and context variable name (I will explain this later).

In the 2nd part (line 11 to 20) we are creating the JavaScript code string which is the entry of our client side AJAX call. Line 11 to 14 are building the JavaScript code including function name, parameters, and join the code we created in the 1st part as the content of our new function.

From line 12 you can see our AJAX method has two parameters: arg and ctx. The names have to be the same string we used in line 6 and 8. I will show you the created html code and you will know why.

   1:  <script type="text/javascript"> 
   2:  //<![CDATA[
   3:  function DoTheCallback(arg, ctx) {
   4:      WebForm_DoCallback('__Page',arg,ClientCallbackFunction,ctx,null,true)}//]]>
   5:  </script>

By doing above things we have finished the hardest part. Now it is time to make our aspx page support client call back. To do so we need the Page class implement ICallBackEventHandler interface.

   1:  public partial class Ajax : System.Web.UI.Page, ICallbackEventHandler
   2:  {
   3:      private string returnValue = string.Empty;
   4:   
   5:      #region ICallbackEventHandler Members
   6:   
   7:      public string GetCallbackResult()
   8:      {
   9:          return "the result you want to pass to client";
  10:      }
  11:   
  12:      public void RaiseCallbackEvent(string eventArgument)
  13:      {
  14:          // handle the eventArgument value to different things
  15:      }
  16:   
  17:      #endregion
  18:  }

ICallBackEventHandler has two methods, the RaiseCallbackEvent method will fire first when client-side calls the AJAX method we created and inside this method we have a chance to handle different call based on the different eventArgument values.

Then the GetCallbakcResult method will be called at here you can return any string value you want. Since RaiseCallbackEvent and GetCallbakcResult are separate we have to find a way to share data between them that is why I declared a private string variable returnValue at line 3. By using so I can set the value by a proper value in RaiseCallbackEvent and return the value in GetCallbakcResult.

Note: the client side DoTheCallback method’s 2nd parameter will never be used in server side, the AJAX call will return exactly the same value to the callback method “ClientCallBackFunction”.

The last thing to do is create a callback function we declared at part one which will handle the AJAX callback call.

   1:      function ClientCallbackFunction(arg, ctx, a, b, c, d, e) {
   2:          //do your client stuff here
   3:      }

The callback method will receive only two parameters, the first one always the return value and the second one always the context string which we passed in when we begin the AJAX call. You can check the values for parameters a to c and they are always null.

ALL DONE. :)

No comments: