When to save a variable in viewstate?
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 be开发者_运维技巧en 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..
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.
(source: microsoft.com)
As per ASP.Net Page Lifecycle Overview (emphasis is mine)
PreLoad()
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request() instance.
....
SaveStateComplete()
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
As both Control Events and the PreRender event occur between these two, then your data should be persisted in ViewState.
Viewstate is maintained via a hidden field, so Postback has to finish before it's "set". If you're setting it and trying to read it in the same page cycle it not going to work. You might try using the Session object, which get/sets values into memory.
精彩评论