AddThis Social Bookmark Button

Print

Using the New Callback Manager in ASP.NET 2.0
Pages: 1, 2

For the second command, the states (or cities) are also separated by commas; for example, Alabama,California,Maryland,Massachusetts,New York,Oklahoma,Wisconsin,.

Next, in the Page_Load event, you need to generate the code that performs the call back using the GetCallbackEventReference method of the Page class:


Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
  Handles Me.Load

  ddlCountry.Attributes.Add("onChange", "GetStatesFromServer()")
  callbackStr = Page.GetCallbackEventReference(Me, "Command", _
                "CallBackHandler", "context", "onError")
End Sub

Essentially, the callbackStr variable will store the following string:


WebForm_DoCallback('__Page',Command,CallBackHandler,context,onError)

What is important here is that Command is referring to the string that is going to be passed to the server, while CallBackHandler means the function that is invoked (on the client) when the server returns a result to the client.

Let's now define the functions on the client side. On the web form, switch to Source view and add in the following script block:


...
</head>
<body>
<script>
function GetStateFromZip(){
  var Command = "1:" + document.forms[0].elements['txtZipCode'].value;
  var context = new Object();
  context.CommandName = "GetStateFromZip";
  <%=callbackStr%>
}
    
function GetStatesFromServer() {
  var Command = "2:" + document.forms[0].elements['ddlCountry'].value;
  var context = new Object();
  context.CommandName = "GetStatesFromCountry";
  <%=callbackStr%>
}
    
function CallBackHandler(result, context) {
  if (context.CommandName == "GetStateFromZip" ) {
    var indexofComma = result.indexOf(",");
    var City = result.substring(0,indexofComma);
    var State = result.substring(indexofComma+1,result.length);
    document.forms[0].elements['txtState'].value = State; 
    document.forms[0].elements['txtCity'].value = City; 
  } else 
  if (context.CommandName == "GetStatesFromCountry")
  {
    document.forms[0].elements['ddlState'].options.length=0;
    while (result.length>0) {
      var indexofComma = result.indexOf(",");
      var State = result.substring(0,indexofComma);
      result = result.substring(indexofComma+1)

      opt = new Option(State,State); 
      document.forms[0].elements['ddlState'].add(opt);
    }
  }
}
    
function onError(message, context) {
  alert("Exception :\n" + message);
}
      
</script>
<form id="form1" runat="server">
...

The GetStateFromZip and GetStatesFromServer functions basically formulate the request to be sent to the server side; in this case, it takes the value of the TextBox control (and DropDownList control) and puts it into the callbackStr. The <%=callbackStr%> statement will insert the generated string into the function, so that during runtime it becomes:


function GetStateFromZip(){
  var Command = "1:" + document.forms[0].elements['txtZipCode'].value;
  var context = new Object();
  context.CommandName = "GetStateFromZip";
  WebForm_DoCallback('__Page',Command,CallBackHandler,context,onError)
}
    
function GetStatesFromServer(){
  var Command = "2:" + document.forms[0].elements['ddlCountry'].value;
  var context = new Object();
  context.CommandName = "GetStatesFromCountry";
  WebForm_DoCallback('__Page',Command,CallBackHandler,context,onError)
}

Notice that both functions return the call to the CallBackHandler function -- the CallBackHandler function will be invoked when the server returns the result to the client. Hence, there is a need to differentiate who the return caller is. I use the context variable to set the command name for each type of call (GetStateFromZip or GetStatesFromCountry).

The result will be returned as the variable result. The result is then parsed and displayed accordingly in the controls on the page.

To complete this example, remember to wire up the Button control with the GetStateFromZip function.


<input id="Button1" type="button" value="Get City and State" 
      OnClick="GetStateFromZip()" 
      style="width: 144px; height: 24px"/>

<asp:DropDownList ID="ddlCountry" Runat="Server" >
  <asp:ListItem>Select Country</asp:ListItem>
  <asp:ListItem Value="US">United States</asp:ListItem>
  <asp:ListItem Value="Sing">Singapore</asp:ListItem>
  <asp:ListItem Value="UK">United Kingdom</asp:ListItem>
</asp:DropDownList>    

<asp:DropDownList ID="ddlState" Runat="server">
</asp:DropDownList>

As for the Country DropDownList control, recall that earlier in the Page_Load event we have this statement:


  ddlCountry.Attributes.Add("onChange", "GetStatesFromServer()")

Essentially, this means that when the item in the DropDownList control changes, the GetStatesFromServer function will be called.

Press F5 to test the application. You can now access the server without a postback (see Figure 2).


Figure 2. Using the Callback Manager to avoid a postback

Note: JavaScript is case-sensitive, so be sure to use the correct case for control names.

Summary

The Callback Manager is a very useful feature in ASP.NET 2.0 that allows you to build responsive web applications. However, notice that the RaiseCallbackEvent function takes in and returns a result of string data type. Therefore, if you have complex data types to transfer from the client to the server (and vice versa), you need to serialize the complex object into a string and then back.

Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.


Return to ONDotnet.com