11 Dec 2007

Callbackia - The land before Ajax

Okay maybe I'm wilfully ignorant but did you know that ASP.NET 2 had asynchronous client-server callbacks afore this AJAX lark began to make our lives so... rich and fulfilling? And from what I've used of them, they are a lot more practicable than the ginger stepchild Ajax.Net PageMethods that I covered previously.

So in essence, here's the gen.

1. Any Asp.Net Page or Control can expose itself to AJAX-style client-side calls and easily perform some server logic before returning some value or other.
2. You just have to implement the System.Web.UI.ICallbackEventHandler interface. This requires two methods, RaiseCallbackEvent(string eventArgument), which receives a request from client-side, and GetCallbackResult() which returns a string to the client.
3. You need to call a special client-script registration method in your ASP.NET code. This example explains it better than I can be bothered to:

string strClientCallbackAutoGubbins = Page.ClientScript.GetCallbackEventReference(this, "RequestArg", "ServerCallResponse", "OptionalContext", true);
string strClientCallbackFunctionCode = "function ServerCall(RequestArg, OptionalContext)" + "{ " + strClientCallbackAutoGubbins + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ServerCall", strClientCallbackFunctionCode, true);

4. Then you just need to implement client script to call the ServerCall client function and get the response back in the
ServerCallResponse client function.

5. The format and purpose of the string argument passed to ServerCall, and the format of the response string returned to
ServerCallResponse is up to you. You could use JSON, XML or any other bloated WEB2.0ism of your choice - or you could do wot i dun and just pass a bog standard querystring along.

ViewState Mayhem

I made a portal app that had little draggable, dynamically loaded ASP.NET webcontrols that you could move around a dashboard. All was fine and dandy until I needed to handle control events in these draggable controls. See, when I moved a control, the viewstate got all munged up and controls started restoring each other's data. WHY WAS THIS SO?

Turns out that by default, ViewState is maintained NOT by an index of ClientIDs but by offset indexes to the parent control. So if you dynamically change the order of controls loaded in a container between first view and postback, ViewState will go boom.

The elusive, and not very satisfactory solution, is the mysterious ViewStateModeById custom attribute. When adorning a class, it ensures the object will have its ViewState keyed by ID instead of by index. Huzzah. Only prob is you need to wrap everything you want to maintain this way in a thin wrapper in order to implement the custom attribute. Oh joy.

Anyway for this and other sexy CustomAttributes you may have missed, check dis:
If I helped you out today, you can buy me a beer below. Cheers!