Wednesday, May 02, 2007

ICallbackEventHandler vs AJAX.NET

There’s been much excitement recently about AJAX and how it provides a rich model for callbacks and client scripting. There’s also been much disappointment in the ASP.NET 2.0 callback implementation with ICallbackEventHandler, especially in contrast to what AJAX does.

As I see it, AJAX provides two things over and beyond ICallbackEventHandler. The first feature is arbitrary parameters to the target method. The implementation uses reflection to map the incoming call onto an arbitrary method and its parameters. This is certainly convenient. The second feature going for it is generating JavaScript objects in the client script that correspond to server side types returned from the callback method. This is also very convenient.

With those two slick features over ICallbackEventHandler, it’s easy to overlook what AJAX doesn’t do well. The primary thing that ICallbackEventHandler has over AJAX is that it integrates very well into the server page lifecycle. This might seem unnecessary and it is if all your callback method is executing code unrelated to the page object on the server (like accessing a database and returning some values, say). But, integrating into the page model is essential if you want to leverage all those server controls.

An interesting technique is to use Control.RenderControl in the callback method. This will ask the control to render itself into a buffer that you have manually constructed. The rendered HTML in the buffer will be the result of your call method. Then in the client there’s little work to do except to take the returned HTML and replace a tag’s innerHTML with those results. Although sorting is an option on the GridView, it works well as an example of this technique that can be used for almost any custom control:
This technique makes the page more efficient because we’ve eliminated the bloated ViewState for the GridView. We post to the server only what we need for it to do its job. And the returned data is just the piece of the page that needs updating. This certainly beats reposting the entire page.After I wrote up this sample, I started wondering how the GridView (and TreeView, for that matter) were implemented when you enable the EnableSortingAndPagingCallbacks property (or EnableClientScript for the TreeView). It turns out they do essentially the same thing. They call RenderControl on themselves and send that back to the client which is then simply replaced in the client DOM. This is definitely a useful technique.

reference : http://staff.develop.com/ballen/blog/PermaLink.aspx?guid=c35c43f6-5686-40ee-9752-8095a848d821

No comments: