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
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 7 of 7.
-
CallBack
2006-08-02 10:36:27 10SNE1 [Reply | View]
Do you have this code for C#. I'm having trouble converting the VB code to C# Interface Programming.
Thanks -
CallBack
2006-10-13 02:05:10 RohanDcosta [Reply | View]
gotta implement 2 methods not one since
The signature of ICallbackEventHandler is:
interface ICallbackEventHandler
{
void RaiseCallbackEvent (string eventArgument);
string GetCallbackResult ()
}
The definition of ICallbackEventHandler itself has changed before it had a final shape in the final release. Here is the old definition of ICallbackEventHandler:
interface ICallbackEventHandler
{
string RaiseCallbackEvent(string eventArgument);
}
string ICallbackEventHandler.GetCallbackResult()
{
return CallbackResult;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
//throw new Exception("The method or operation is not implemented.");
//switch(eventArgument.StartsWith("1:"))
switch (eventArgument.Substring(0, 2))
{
case "1:":
{
eventArgument = eventArgument.Substring(2);
switch (eventArgument)
{
case "95472": CallbackResult = "Sebastopol,CA";
break;
case "02140": CallbackResult = "Cambridge,MA";
break;
default: CallbackResult = "ZipCode not valid.";
break;
//default: return "ZipCode not valid.";
}
}
break;
case ("2:"):
{
eventArgument = eventArgument.Substring(2);
switch (eventArgument)
{
case "Sing": CallbackResult = "Singapore,";
break;
case "US": CallbackResult = "Alabama,California,Maryland,Massachusetts,New York,Oklahoma,Wisconsin,";
break;
case "UK": CallbackResult = "Birmingham,Cambridge,Christchurch,Leeds,Sheffield,";
break;
default: CallbackResult = "ZipCode not valid."; break;
}
}
break;
default: CallbackResult = "case cannot be recognized"; break;
}
}
------SCRIPTS--------------
function GetStateFromZip()
{
//alert('hit GetStateFromZip');
//debugger;
var command = "1:"+document.form1.elements("txtPinCode").value;
var context = new Object();
context.CommandName = "GetStateFromZip";
<%=CAllbackString%>;
}
function GetStatesFromServer()
{
//alert('hit GetStateFromZip');
//debugger;
var command = "2:"+document.form1.elements('ddlCountry').value
var context = new Object();
context.CommandName = "GetStatesFromCountry";
<%=CAllbackString%>;
}
function ClientCallBackHandler(result,context)
{
//alert('hit ClientCallBackHandler');
debugger;
if(context.CommandName == "GetStateFromZip")
{
var indexOfComma = result.indexOf(",");
var City = result.substring(0,indexOfComma);
var State = result.substring(indexOfComma+1,result.length);
document.form1.elements("txtState").value = State;
document.form1.elements("txtCity").value = City;
}
else
{
if(context.CommandName == "GetStatesFromCountry")
{
var indexOfComma = 0;
document.form1.elements("ddlState").options.length = 0;
while((result.length > 0) && (indexOfComma != -1))
{
indexOfComma = result.indexOf(",");
var State = result.substring(0,indexOfComma);
result = result.substring(indexOfComma+1);
opt = new Option(State,State);
document.form1.elements("ddlState").add(opt);
}
}
}
}
function OnError(message,context)
{
alert("Exception :-" + message);
}
---------
HAve Fun :)
-
user registration with random images
2006-05-10 00:23:34 erika1978 [Reply | View]
What about using Callback Manager during user registration?
In this way, we could avoid tha postback and freely test (without using web services)if the number the user has inserted correspond to that of a random image.
What do you think about it?
-
Several other good resources
2004-08-13 06:32:01 alovera [Reply | View]
Here are several other good resources - each of which should work on the .Net 1.x Framework as well.
Implement Script Callback Framework in ASP.NET 1.x: Good, but possibly IE specific
Thycotic Software Ltd - .NET - Remote Scripting Client (without applet) for .NET and ASP: Cross browser compatible - based on JSRS.
-
non-MSIE?
2004-08-10 08:24:47 willer [Reply | View]
This looks neat... it's not exactly automatic, because there's all that client-side code you have to write.
I was wondering, when you print that callback code into the client-side javascript functions, is that autogenerated code MSIE-only? I seem to recall that xmlrpc works differently in Mozilla/Firefox, and I have a feeling the MS guys didn't bother supporting it. -
non-MSIE?
2004-08-12 07:51:07 jpatel [Reply | View]
There's a MSDN article that shows how to implement the callback mechanism in ASP.Net 1.x. It seems conceivable that it could be implemented in Mozilla as well since it has an XmlHttp type capability
Does the author have any input in this area?
---
I've posted some additional resources that may be useful.






There would be state/province, country, gender, first name, last name, dob, and so on. Do you have code done already for this? Or know of a site that has the code done. I appreciate your help.