Friday, June 10, 2011

Javascript and .NET PostBacks

I always find it interesting when I suddenly find a use for a feature of a toolkit that I never needed before. This is the story of one such event, which just happened today.

Some background: I'm working on the accounting portion of my new company's product. It is almost ready to unveil; I just have to finish a couple of data entry screens and generate the core reports. Currently, I'm working on the bank account reconciliation page.

I want it to be nicely interactive - when you check an item off, I want to immediately update the item counts and totals so that the user can see their progress toward balanced. The most effective way to do this is to use javascript, and so that is what I did.

It worked great. But I have a handful of things that require a server round-trip, or a post back. When these happened, my totals were reset. This makes sense, the server-side couldn't possibly know what all had happened since it last sent the pages. This means that I have to figure out what the user had been doing, and have my server-side code reproduce the calculations the client-side was doing (I know I could have stored the values in hidden fields, I chose not to and I'm glad, because then this story wouldn't have happened).

Where to do these calculations? The answer is to handle them in Page_Load. I've done lots of coding in Page_Load, but never in response to a post-back. My pages mostly look a lot like this:

protected void Page_Load(object sender, EventArgs e) {
    if (IsPostBack) {
    } else {
        // Lots of code here to load the page from 
        // query strings and other stuff.

I almost never had any code in the side of the if statement when IsPostBack was true. I had about decided I never would. But here was a case where I needed to fill my page only on a post-back.

Nothing really profound, but I just think it is interesting when something new comes up for me.

No comments: