I'm having some problems in persisting the viewstate on postback for a Control (vb.net)
here's some code i've put in my control:
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
Me.EnableViewState = True
Me.ViewStateMode = System.Web.UI.ViewStateMode.Enabled
If Not Page.IsPostBack Then
_SortTime = DateTime.Now
_SortTime.AddSeconds(-10) ' incase the fileserver and webserver date are out of sync
ViewState("PageLoadTimeStamp") = _SortTime
End If
End Sub
onload:
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
_SortTime = CType(ViewState("PageLoadTimeStamp"), DateTime)
End Sub
But on every postback, the viewstate is empty again.
Update: What do i want to do?
I want to store the time when the user first loads the page. Then, the user will do multiple postbacks. On every postback i need to know that time.
Update 2: Context:
- An aspx page (Editor.aspx) will load a web control (ObjectsEditor.ascx) dynamicly
- ObjectsEditor.ascx contains of a single custom control (Objects.vb)
- Objects.vb will create another custom control (ObjectsContainer.vb) and add it to it's controls
It is the ObjectsContainer that needs to persist the viewstate.
I'm setting EnableViewState = "true" everywhere i can, but still no result. Do i really need to set those properties here. (ViewStateMode and EnableViewState) If not, where should i handle this and what is the difference between those properties?
Many thanks.
Best Answer
I see some correct answers here, but I don't see any detailed explanations, so I figured I would chime in:
ASP.NET has a fairly complicated request/response life-cycle. Each cycle runs through a set of events such as
Init
,Load
, etc.. According to this article, and specifically this image, there is a method calledTrackViewState()
that executes after theInit
event but beforeInitComplete
event. This means that any changes toViewState
will not be persisted (tracked) if they are made in theInit
event like the OP has done.There is an additional method called
LoadViewState()
that takes theViewState
data that was posted via the__VIEWSTATE
form value and loads it into the currentViewState
collection. This executes after theInitComplete
event but before thePreLoad
event. Meaning that values already set toViewState
beforeLoadViewState()
executes will likely be overwritten.Now, knowing when these 2 events occur, and knowing the
ViewState
persistence methods that execute before and after them, we can deduce that the earliest event where it is safe to setViewState
values is thePreLoad
event. Values set earlier than this event will likely be overwritten and thus not persisted.So, to answer your question, set your
ViewState
value in theOnPreLoad()
method or do as others have suggested and do it in theOnLoad()
method and your values should be persisted.