Tuesday, June 26, 2007

ViewState and Page Life Cycle

TRULY Understanding ViewState
The ASP.NET Page Life Cycle


About ViewState:
1. Server Controls utilize ViewState as the backing store for most, if not all their properties.
2. TrackViewState will turn tracking ON, and ONLY when tracking is ON, any changes to any of the StateBag's values will cause that item to be marked as "Dirty".
3. TrackViewState was call during the OnInit phase of the page/control lifecycle.
4. When the StateBag is asked to save and return it's state (StateBag.SaveViewState()), it only does so for the items contained within it that are marked as Dirty.
5. In the case of ViewState backing, setting the property to NULL will result in resetting the property back to it's default value.

WHAT DOESN'T VIEWSTATE DO?
  1. Remember any state information across page loads (only postbacks) (that is unless you customize how the data is persisted)
  2. Remove the need to repopulate data on every request
  3. ViewState is not responsible for the population of values that are posted such as by TextBox controls (although it does play an important role)

Page life cycle:

  1. Initialization
  2. LoadViewState (occurs only on PostBack)
  3. LoadPostDackData (occurs only on PostBack)
  4. Load
  5. RaisePostBacKEvent (occurs only on PostBack)
  6. SaveViewState
  7. Render
3 common ASP.NET AJAX mistakes

Page events still fire during partial postbacks
Use IsPostBack and IsInAsyncPostBack to avoid accidental execution of Page_Load code during partial postbacks
In conjunction with __doPostBack, __EVENTTARGET may be used to limit UpdatePanel life cycle event execution to only the targeted panel

UpdatePanel events fire on each and every request

if (Request["__EVENTTARGET"] == UpdatePanel1.ClientID)
{
// Insert magic here.
}

Control events are raised after Load events
By using PreRender instead of Load, you can allow control events to be handled before your code executes





No comments: