Reader Level:
ARTICLE

Calling the Server-Side method asynchronously from Client Script

Posted by Dipen Lama Articles | Visual C# July 19, 2006
This article describes how to call the server-side method asynchronously from JavaScript with the use of Client Callbacks that is built in ASP.NET 2 so that the client browser receives the data dynamically without page postback.
  • 0
  • 0
  • 42607
Download Files:
 

Client Callbacks

Client Callbacks is a new feature of ASP.NET 2 which allow client side script to call server side method asynchronously without post back to fetch new data from server and change the display in client brower dynamically.

Developer use JavaScript mainly to make the page more interactive and to avoid page postback. But there are often situation where post back of page is necessary to fetch new data from the server/database. Consider a scenerio where we have a dropdown list of Countries and a listbox of the cities. The listbox cities should display the cities based on the selected country from the dropdown list.

 

Now in this case we have to post back the page when the Country dropdown item is changes and fill the Cities listbox with the new items fetched form the database based on the Country selected. The simple way to do avoid postback is to use Client Callbacks where the JavaScript code will communicate with the server and refresh the Cities listbox without postback.

The following procedure has to be followed to create Client Callbacks:

Step 1:

To receive the call back from the client the page must implement the ICallbackEventHandler interface.

public partial class ClientCallbackPage : System.Web.UI.Page, ICallbackEventHandler

{

 

}

Step 2:

The ICallbackEventHandler has two methods RaiseCallBackEvent() that receives data from the client browser as a string agrument which is triggered first and GetCallbackResult() that provides the data to the client browser and is trigger next.

In our example, we will pass the Selected Country value to the server in the RaiseCallBackEvent()

public void RaiseCallbackEvent(string callbackEventArgument)

{

        m_callbackEventArgument = callbackEventArgument;
}

m_callbackEventArgument is a private string member variable and we will assign the selected country value passed from the client browser on it. Now in the GetCallbackResult() method we can retrieve the cities list for the selected country from the database or any other datastore and passed the cities list back to the client browser. Here in this example I have just hardcoded the cities list that is suppose to come from database.

public string GetCallbackResult()

{

   string callbackResult = String.Empty;

   if (m_callbackEventArgument.Equals("India"))

   {

      callbackResult += "New Delhi|New   
                         Delhi;Mumbai|Mumbai;Kolkata|Kolkata;"
;

   }

   if (m_callbackEventArgument.Equals("China"))

   {

      callbackResult += "Bejing|Bejing;Shanghai|Shanghai;Xian|Xian;";

   }

   return callbackResult;
}

The main limitation of ASP.NET Client Callback is that you can send data to the client only as a single string. So, we are sending the cities list to the client browser as string seperated with ";" character and "|" character to separte the text and value field of the city. If you have to pass a complex data such as your collection of business object data then you need to design a way to serialize the data into string and deserialize the string on the client browser with JavaScript. One way is have a xml string and passed it and on the client side it can be parsed with JavaScript either with the built in xml parser or your own.

Step 3:

The third step is to write a client script which will receive the data from the server and deserialize it and display it on the browser. We can give any name to the JavaScript method which handles the callback response from the server but should have two arguments.

function ClientCallbackScript(result, context)

{

  var lstCity = document.forms[0].elements['lstCity'];

  lstCity.innerHTML= "";

  var cities = result.split(';');

  for (var i = 0; i < cities.length - 1; ++i)

  {

    var properties = cities[i].split('|');

    var cityName = properties[0];

    var cityId = properties[1];

    var option = document.createElement("option");

    option.value = cityId;

    option.innerHTML = cityName;

    lstCity.appendChild(option);

 }
}

Here the result parameter holds the data that is send by the server and now this has to be parsed and filled up in the cities listbox.

Step 4:

Now the final step is to define the event in which the Callback trigger is fired. Here in our case we will define the Callback trigger to fire on the Country dropdown list changed event.

protected void Page_Load(object sender, EventArgs e)

{

   if (! Page.IsPostBack)

   {

       FillCountryList();

       FillCityList(ddlCountry.SelectedValue);

       string callbackEventReference =   
       Page.ClientScript.GetCallbackEventReference(this,
         "document.all['ddlCountry'].value", "ClientCallbackScript",  
         "null");

       ddlCountry.Attributes["onclick"] = callbackEventReference;

    }
}

The Page.ClientScript.GetCallbackEventReference returns a JavaScript code that calls the Client Callback. The first agruments it take is the ICallBackEventHandler object that will handle the callback that is the page itself in our case. The second argument is the data that the client browser will pass to the server i.e selected Country from the dropdown list. The third argument is the name of the JavaScript method that will receive the data from the server callback. And the last argument is the Context information that we want to pass. Here we are passing null.

Below is the complete sequence diagram of the above process

COMMENT USING

Trending up