When to save a variable in viewstate

asp.net

I have searched the web for the answer and saw that mostly variables are saved in viewstate on page.prerender event. Then the value of the variable is set back in page load event.

However, when I save a variable in viewstate on prerender or load events, how can viewstate store the value of the variable after it is changed dynamically on codebehind?

Let's say, after page is loaded, user clicked a button which changes the value of the variable in its onClick event. Then the postback event raised since the button was clicked. According to me, the new value should have been lost and cannot be saved in the viewstate if the variable is saved in the viewstate only in prerender event. Because on postback the prerender event wont fire and the value cannot be saved.

Shouldn't I save the variable in the viewstate just before the postback event rises?

Am I wrong? If so, how can viewstate store the new value of the variable if the viewstate is saved in prerender event?

Thanks for the answer in advance..

Best Answer

I suspect you're confusing saving ViewState, ie. serializing the ViewState collection in memory to a string representation or to an intermediate object that can be serialized easily, with actually modifying that ViewState in-memory object with its regular accessor methods.

What you may be hearing is that the SaveViewState() method is called after PreRender event. But that has little to do with when you get to modify the contents of the ViewState collection.

Checkout points 7. Prerender the Objects and 8. ViewState Saved in the article The ASP.NET Page Life Cycle. There's a good MSDN article that touches on this as well.

alt text
(source: microsoft.com)

Related Topic