Asynchronous Callbacks
I was playing with the new Asynchronous Callbacks in Whidbey today... very nice! Basically, what they allow you to do is to, effectively, call server-side code from the client-side without invoking a Page postback.
Picture this, imagine that you need to do client-side e-mail validation in your page; not just regex validation; real stuff. You have to do a real-time check to confirm that the mail address exists. Here's how you could do that using Asynchronous Callbacks.
1) Implement an Interface
In your page you implement the System.Web.UI.ICallbackEventHandler interface and add code for the RaiseCallbackEvent method which is a method that receives an Asynch call (as a string) and returns data to the callee (again as a string).<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %> ' ICallbackEventHandler implementation Protected Function RaiseCallbackEvent(ByVal arg As String) As String _ Implements ICallbackEventHandler.RaiseCallbackEvent If IsNumeric(arg) Then Return "Good Data" Else Throw New ArgumentException("You cannot use that type of data. Must be numeric.") End If End Function
2) Do the wiring-up
There's a method on the Page class which emits a javascript string suitable for calling the RaiseCallbackEvent method asynchronously. The method is named: "GetCallbackEventReference". To use it you basically tell it what client-side method will handle the callback and another client-side method to call just in case an error occurs.
' a string which will hold the callback javascript Public Atts As String Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) If Not IsPostBack Then ' __CallbackHandler is a javascript method to callback ' __CallbackError is a javascript method to callback in case an error occurs Atts = Me.GetCallbackEventReference(Me, "myClientSideVar", "__CallbackHandler", _ Nothing, "__CallbackError") End If End Sub
3) Invoke the call from the client
Add some client-side functions to: A) invoke the asynch. callback, B) receive the asynch. response, C) handle and errors. Note that the names match the names which were passed to the GetCallbackEventReference method on the server.
// a processing function which requires an asynch call function DoStuff() { alert("about to do callback") var myClientSideVar = txtField.value ; <%= Atts %> // this will write out the javascript to invoke the callback alert("just did the callback") } // the callback function function __CallbackHandler(result, context) { alert( result ) ; } // the callback function in case of an error function __CallbackError(message, context) { alert( "An error occurred: " + message ) ; }
So now, whenever the DoStuff() function is called, an asynch call will be made and processing will continue on through to the end of DoStuff. Eventually the callback will return through either "__CallbackHandler" or "__CallbackError".
There's an article on DotNetJunkies today which shows a great little application which uses this very logic.