Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET

Client Callbacks in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.67/5 (2 votes)
2 Jul 2009CPOL4 min read 21.9K   17  
Client callbacks in ASP.NET

By default, ASP.NET pages communicate with the server through a mechanism called “PostBack”. Postback is very useful and efficient, except for the cases, where:

  1. You have a huge page, with a lot of processing required at server, so doing all that processing on every postback is not only waste of resources on the server, but also hurts the user experience.
  2. You have client side variable, which will be lost on page refresh (i.e., postback).

You can avoid both these limitations by introducing Client Callbacks in your application. In a client callback, a client side event makes a request to the server, at server the page is initiated, it members are created, however page runs a modified version of its life cycle and the only method that is marked for invocation is called; that, then can return a value that can be read using another client side function.

Throughout this process, page is available to the user and results are quick in most of the cases as only a small amount of data is being exchanged between client and the server.

To implement client callbacks, you need to do some work, both on server side as well as client side.

On server side, you need to:

  1. Implement ICallBackEventHandler in the page, that you want to use callbacks in. It have two methods, i.e., RaiseCallbackEvent and GetCallbackResults.
  2. Provide implementation for RaiseCallBackEvent, this is the method that is invoked by the client to perform callbacks. This method accepts string as an argument.
  3. Provide implementation for GetCallbackResults, this method is invoked by the server, to process the request and return the results to the client as a string.
  4. Retrieve a reference of a client side function (Using ClientScript.GetCallbackEventReference method), this function will be invoked as the result of server side processing, and it can be used to process any results coming back from server.
  5. Register a client side script, using Page.ClientScript.RegisterClientScriptBlock method, that will make a call to the server.

On ClientSide, you need to:

  1. Implement the function that you provided as an argument in step 4 above.
  2. Call the function you registered in step 5 above, on a client side event.

Let's look at the code that you will use to implement your client call backs. In our demo project, we have two comboboxes on our ASP.NET page. One contains a list of departments and other a list of employees in the selected department. What we want to do is, fill employee combobox with the respective department employees, whenever our user changes department in Department combobox, without doing a postback.

First things First; Implement ICallbackEventHandler interface:

C#
public partial class _Default : System.Web.UI.Page,ICallbackEventHandler

Implement two methods of ICallbackEventHandler:

C#
#region ICallbackEventHandler Members 
    /// <summary> 
    /// this method Returns the results of a callback event. 
    /// </summary> 
    /// <returns></returns> 
    public string GetCallbackResult()     { 
        //as only strings can be sent back to the client, we are will iterate
        //through the list of  employees and convert it into comma delimited string 
        string employeelist=""; 

        foreach (Department dept in departmetList) 
        { 
            if (dept.Name == deptArg) 
            { 
                foreach (Employee emp in dept.Employeelist) 
                { 
                    employeelist += emp.Name; 
                    employeelist += ","; 
                } 
            } 
        } 

        return employeelist; 
    } 

    /// <summary> 
    /// This method is invoked by the client, this will be used to receive parameter
    /// values from the client 
    /// </summary> 
    /// <param name="eventArgument"></param> 
    public void RaiseCallbackEvent(string eventArgument)     { 
        //right now all we are doing is to set the class level variable to eventArgument 
        //that was sent by the client, recall that it is departments name. 
        deptArg = eventArgument; 
    }

In your page_load event handler, first retrieve the reference of client function that will be invoked as the result of call back using ClientScriptManager.GetCallbackEventReference:

C#
string callbackEventReference = Page.ClientScript.GetCallbackEventReference(this,
    "arg", "GetResults", "");

This method has several overloads, the one we have used takes target (in this case “page”), the “argument” that was passed by the client, name of the client side event handler that received the result of callback event and context as arguments. Context is any client script that will be evaluated prior to making a callback request. In this case, we have passed an empty string.

Then, you need to build and register a client side script, that will call this CallBackEventReference, this is the script that will make the call to the server.

C#
string callbackScript; 

callbackScript = "function CallServer(arg){" + callbackEventReference + ";}"; 

//register callbackScript with the client using
// ClientScriptManager.RegisterClientScriptBlock 
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer",
    callbackScript, true);

So this was all that you need to do in our server side code, and now we will look at the client side code that we need to write to complete our client Callback.

First, we will write the function (using ECMAScript) in script block of our aspx file, GetResults; that we have been referencing in our code above.

C#
function GetResults(result)
{
    if(result!="")
    {
    var array=result.split(",");
    for (var i=0;i<array.length;i++) {
    option = new Option(array[i],array[i]);
    var slc_target = document.getElementById("ddlEmployee");
    slc_target.options[i] = option;
    }

    }
    else
    {
    //do something
    }
}

This function is accepting results; which is a string and it is splitting it into an array. Then all it does is, bind “ddlEmployee”, a combobox on the page, with this array.

And finally on a client side event of another combobox, “ddlDept”, we will invoke “CallServer” client side function that we registered using our serverside code and we will pass department as an argument.

ASP.NET
<asp:DropDownList Width="100" ID="ddlDept" runat="server" 
    OnChange="CallServer(ddlDept.value)">

I have attached the demo VS 2008 solution here. When you run the project, you can see that whenever you change any value in the Department Combo box, values in Employees combobox are refreshed without making a postback to the server.

And happy programming!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Being an software developer, trying to understand the problem, trying to figure out how best it can be solved and then going through the joy of implementing a solution, continously improving it and watching it becoming part of peoples live has been my passion and primary reason that i love my job so much.

I specialise in .Net Framework, C# language, ASP.Net, Distributed Applications using WCF and Web Services (WS.* and REST), WPF, WF and Ajax along with SQL Server.

I have sense of accomplishment and satisfaction that i have been involved in many successful software development projects since last 9 years and since last 6 years i have been working on this exciting technology called .Net Framework and it brings me such a joy that since then both .Net Framework and Myself (professionally!) have been growing together. Next destination in our journey is “THE CLOUD”.

Comments and Discussions

 
-- There are no messages in this forum --