Weird trap while using WebForm_DoCallback() inside my external client scripts
Today, while I was trying to move large portions of a web
application I'm working on from
Ajax.NET to
ASP.NET AJAX and callback
support, I've bumbed into a weird trap related to how
callback targets are resolved at server side.
The story
begins with me trying to adapt a custom control in such a
way that events that originally got fired at client side
through the elegant Ajax.NET APIs would instead get fired
via ASP.NET callback; the reason behind this decision is
twofold.
First of all, I've chosen to leave behind
Ajax.NET because I'd like to start using a "standard"
library for my ajax behaviors. Even if I've never run into
any problems using Ajax.NET and I've loved it for quite some
time, I hope Microsoft will make their best effort to
support and integrate this platform inside the ASP.NET
framework, even better than any other ISV could. Then, why
callbacks and not, for example, async postbacks? Well, to my
surprise, I've ascertained async postbacks are quite verbose
in their communications. Since my project goals include
saving as much bandwidth as possible, I've looked for an
alternative. Callbacks come to my rescue... And average
payloads of this technology are very similar to Ajax.NET
ones.
Back to my original problem. I started
preparing my control for callbacks support: I've coded its
implementetion for ICallbackEventHandler
interface and called
ClientScript.GetCallbackEventReference() in its
OnInit (...in vain, just to setup the callback support. Very
annoying!). Now I was trying to use the WebForm_DoCallback
function inside my javascript code; yes, I'm using an
external script file, so I've no way to use the
ClientScript.GetCallbackEventReference() method to obtain
what I was looking for.
At first, it seems
WebForm_DoCallback expects the control ID of the target
as its first argument. So, I've retrieved the control's
ClientID and fed WebForm_DoCallback with it. Everything
worked as expected and I was very happy: the test page that
was hosting my control played very nice.
But, suddenly
after I've moved my control inside another page, a page
which uses a master page, the trick ceased to work. After my
callback started, the page on the server side answer with an
exception saying: "The target ... for the callback could not be found or did
not implement ICallbackEventHandler.".
I will not tell you how much time I've spent in
trying to understand what was wrong with my code...
In
short, the answer to my problem was that
WebForm_DoCallback() does expect the UniqueID of the target
control, not the ClientID. If you miss this point, you will
get callback support that wouldn't work with master pages!
Very easy to fall into this trap...