Saturday, February 11, 2012

Intercept Postbacks

Introduction

Why intercept postbacks? Here is a use case. Your users ask for an Excel-like page to edit multiple records at the same time. No big deal! ISD's EditTable page looks just like an Excel sheet out of the box. You can implement the page in less than 5 minutes with minimal customization. However, there is a tricky issue. If a user pages/sorts/filters the table without saving existing changes, any unsaved changes will lost. It is not an acceptable solution to educate your users to always click the Save button before paging/sorting/filtering. There is no question that you have to save changes automatically. The question is how to implement it.

Brute-Force Implementation

A brute-force implementation is to add code to all event handlers of paging/sorting/filtering. For example,



Repeat this 4 times for PreviousPage, FirstPage, LastPage, and PageSizeButton. There are 10 sortable columns. Repeat 10 more times on the column headers' click event handlers. There are 5 filters above the table control. Repeat another 5 times. Even though you can refactor the try block into a method, so that it is reusable in the event handlers, there are still a lot of boilerplate code.

Better Implementation

A better implementation is to intercept a postback earlier in page load event, and check which control initiates the postback. If it is one of the above mentioned controls, execute SaveData(). Otherwise, return execution to normal life cycle.


Conclusion

If you find yourself doing the same thing again and again in many postback events, try intercepting the postbacks.

No comments: