Client Callbacks are probably the less known (and I dare say, less loved) of all the AJAX options in ASP.NET, which also include the UpdatePanel, Page Methods and Web Services. The reason for that, I believe, is it’s relative complexity:
- Dynamically register function that calls the above reference;
So, here’s what I want to do:
- Have a DOM element which exposes a method that is executed server side, passing it a string and returning a string;
- Have a server-side event that handles the client-side call;
- Have two client-side user-supplied callback functions for handling the success and error results.
The control itself looks like this:
And the event argument class:
You will notice two properties on the CallbackControl:
Async: indicates if the call should be made asynchronously or synchronously (the default);
SendAllData: indicates if the callback call will include the view and control state of all of the controls on the page, so that, on the server side, they will have their properties set when the Callback event is fired.
The CallbackEventArgs class exposes two properties:
Argument: the read-only argument passed to the client-side function;
Result: the result to return to the client-side callback function, set from the Callback event handler.
An example of an handler for the Callback event would be:
Finally, in order to fire the Callback event from the client, you only need this:
The syntax of the callback function is:
arg: some string argument;
context: some context that will be passed to the callback functions (success or failure);
callbackSuccessFunction: some function that will be called when the callback succeeds;
callbackFailureFunction: some function that will be called if the callback fails for some reason.
Give it a try and see if it helps!