Exposing User Control client events to host Page server side
Download Source Solution:
Server side events handling is a great feature of ASP.NET. You can enjoy your server side framework which is usually easier to maintain than your client side code.
One of the drawbacks of server side events handling is the Postback, in which the request is send to the server with all its weight and the response renders the whole HTML again - the user suffers from a visual effect in which the page he’s viewing disappears and reappearing after it finished his rendering process again.
Of course with ASP.NET AJAX, we now have the great UpdatePanel control which hides the postback visual effect from our users and reduces the request weight and renders the HTML part we intended to update. Still, the UpdatePanel control has some drawbacks which one of them is that it carries extra data with it.
Consider a scenario in which you have your user control hosted inside a page and you would like to handle one of your user control’s events on your hosting page, but you want to do it on the server side of your page, and you don’t want to postback the page for this task.
In order to achieve the effect that is described above, we can use a ASP.NET 2.0 feature which is called Callback, which will start the bubbling process we would like to achieve.
Our user control will have to include an event handler in order to bubble the event to his hosts (the hosting page in our case):
Our user control would implement the ICallbackEventHandler in order to use the Callback feature:
The interface implementation involves two methods:
What is left for us to do is setting the code for the client side. We’ll start with preparing the code for the Callback at our user control PreRender event handler:
The code which is written above does the following: it creates a JavaScript function called BubbleEvent which would contain the Callback call to the server side (the actual call is generated by the ClientScriptManager.GetCallbackEventReference method) and the reference to another JavaScript function – ReceiveServerEventBubbleResponse – which will be called when the server side work ends. The JavaScript script is injected to the control by the ClientScriptManager.RegisterClientScriptBlock method.
Next, we need to define our control HTML and JavaScript as the following:
And now all there is left for us to do, is using our user control in a page. First register the control:
Then place it into the page HTML:
And now just register to the event and define the event handler on the page server side code:
Summary
In this post I reviewed a way to bubble client event to the server side, so I can use the power of the server side without the drawbacks of the postback.
Hope you’ll find it useful.