Client Side Callbacks (AJAX technique)

7

Category : Ajax

After a few SharePoint posts I decided I should post some interesting things in .net. Client Side Callbacks have been something I have been using for years and I have always wondered why they don’t get more press. Client Side Callbacks are basically .nets way of wrapping the XmlHttpRequest object. As any good web developer knows (who implements Ajax) – all Ajax is is a buzzword for Asynchronous javascript and xml. However, all “real” Ajax technologies use the XmlHttpRequest to asynchrounously call the server. In fact, one of my big pet-pieves is when people use the word Ajax incorrectly (however, that is for another discussion).

So, to implement Ajax you don’t really need any of these “toolkits” like Ajax.net (formerly Atlas) or Ajax pro. These are just “toolkits” to help you implement Ajax technologies. I have found that these toolkits can produce bloatted javascript and can actually slow down an application if not used correctly. Thus, whenever I have a simple Ajax need I try to use .nets Client Side Callbacks instead of an Ajax toolkit. With that said, there are good uses for these toolkits if your business requirements meet some of their features. It is up to a good architect to determine when these should be used.

The Client Side Callback feature is available in .net 1.1 and 2.0 forward. However, the version in 1.1 is a little lacking, so I will concentrate this blog on the 2.0 version forward.

The simplest need for Ajax is to call the server asynchrounously, allow it to process information, make a call back to the client and allow the client to show the information on the screen (using javascript). The following example will show how to call the server (to get the datetime from the server) and have that datetime show up on the screen without any postbacks.

  1. First create your website and go to the code behind of your default.aspx.
  2. Implement the System.Web.UI.ICallbackEventHandler on the class.
  3. This interface will produce two methods (RaiseCallbackEvent and GetCallbackResult). Make sure both of these methods get implemented.
  4. The RaiseCallbackEvent method will be the first method called when the Callback starts. This method takes in an argument, which you can store as a member variable on your class to use in the GetCallbackResult. The GetCallbackResult method is the method in which you will build the arguments to pass back to the client side javascript.
  5. Implement the code within the RaiseCallbackEvent and GetCallbackResult methods:
  6. 
    private string _argument = string.Empty;
    
    /// The RasieCallbackEvent is the first place to receive the callback from the client's browswer when 'CallServer'
    /// is triggered.parameter passed from the Javascript's call 'CallServer'
    public void RaiseCallbackEvent(string eventArgument)
    {
    //store the argument in a local variable so we can use it in the "GetCallbackResult" method
    //later on if necessary.
    _argument = eventArgument;
    }
    
    /// The GetCallbackResult method is the second call triggered by the 'CallServer()'
    /// on the client side. This is the place to prepare a string that can be placed as
    /// html on the page.
    public string GetCallbackResult()
    {
    //run the code to add the html to the javascript callback method
    if (_argument == "getServerTimeUserControl")
    {
    //return the html
    return System.DateTime.Now.ToString();
    }
    else
    {
    return string.Empty;
    }
    }
    
  7. Next implement the page_load method like this:
  8. 
    protected void Page_Load(object sender, EventArgs e)
    {
    //only need to register once, so don't register when a callback is being performed
    if (!Page.IsCallback)
    {
    //Register the Ajax client script to the client's broswer
    string eventReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
    string callbackScript = "function CallServer(arg, context)" + "{ " + eventReference + "} ;";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
    }
    }
    
  9. The page_load is registering client side scripts, so next we have to go to the default.aspx webpage and build those javascript methods:
  10. 
    function GetServerTime(argument)
    {
    //Send the request to server
    CallServer(argument, "");
    }
    
    function ReceiveServerData(argument)
    {
    document.getElementById("serverTimeUserControlArea").innerHTML = argument;
    }
    
    The ReceiveServerData is the javascript method we registerd in the page_load of the code behind, so that is the method that the client side callback will eventually write back to. The GetServerTime is our javascript method we are going to call to kick off the client side callback functionality.
  11. Build the html. This will just consist of a button to start the client side callback and a div to fill in when the information is retrieved from the server:
  12. <input type=”button” onclick=”javascript:GetServerTime(‘getServerTimeUserControl’);” id=”Button1″ />
    <div runat=”server” id=”serverTimeUserControlArea”></div>

    Thats it!
    It is that easy to implement your own, custom, Ajax solution in .net. You don’t need to implement any third party Ajax solutions to get this to work. Now that you have seen the simplest example you can use your imagination to do more complicated things. For example: You could load up user controls and render their html out to the client side with these techniques. Just be careful because the post-back never occurs, which means certain server side things never happen. You will have to play around with the technique to see what you get.

    Attached is my default.aspx and default.aspx.cs files from the example:
    Default page
    default page code behind

Comments (7)

Greg,

Really cool blog. Loved this technique. It saved me from a lot of complicated work! Thanks for posting it.

Great tip :) Thanks

Wonderful article explained wonderfully
cheers to the programming spirit :)

Hi,

Can we pass multiple inputs to the Server method…???
Would be a great help if u reply

No, unfortunately you can’t. The way I usually deal with this is a unique string seperator. Then, when I get to the server side I do a split on that seperator. Another way to deal with it is to build real xml as your inputs. Then you can get anything out of that. But, I am usually too lazy for that and just use string seperators.

Nice post all together. Please visit the below link for an alternate technique to ajax
http://vipinc007.blogspot.com/2008/09/by-now-nearly-everyone-who-works-in-web.html

For more alternate AJAX techniques check this url

http://vipinc007.blogspot.com/2009/03/ajax-few-new-techniques-without.html

Post a comment