Tuesday, February 24, 2009

Persisting values in web applications

Another thing I would like to caution against is the use of global variables in the .cs files in web-forms - I just saw an example of this in EditLineItem.ascx (isSerialized)

Please remember that unlike windows forms, web-forms do not stay in memory between events on the page (post backs). The object is disposed after every load / post-back (That’s why the page_load is called on every refresh / post-back)
So if you store a value in a public variable in one event of the page, it will revert back to the default in the next.

The viewstate is the ideal place to persist values between post-backs. The general thumb-rule for persisting values in web apps is

Viewstate for storing values on a PAGE (will only be available for that one page for that one session) between post-backs

Session for storing values across pages for one SESSION

Application for storing values across the application lifetime (between IIS-resets, the value will be available to all sessions and in all pages)

No comments:

Post a Comment