Last post May 07, 2015 09:36 AM by mgebhard
May 06, 2015 03:19 PM|hambi|LINK
I am dynamically loading user controls within the Page_Init method. I also dynamically load data to the controls from the database. That all works fine.
I'm not entirely sure how the viewstate works.
At the moment if I make sure I reload a user control during the init phase of the page cycle and ensure it has the same "id" as it had previously then the viewstate matches up and the control's content/values are loaded from the viewstate.
Thus if I have userControl1 with id="xyz1" then it will work as long as I reload it each postback during the init method and set id="xyz1".
I wanted to know is what happens if I drop userControl1 and on a postback load userControl2 with id="xyz2". Does the viewstate automatically drop the info for id="xyz1" (ie userControl1)? I am assuming that the viewstate is rebuilt each postback based on
the controls on the page at that time.
One of my concerns is that my page may be used for a long time with many postbacks and many evolutions in the loaded controls. I didn't want the viewstate continually expanding (ie increasing to include new content but not discarding redundant/old information).
My priority is just to double check that there is nothing that I have to take care of to achieve a stable robust solution. However, also interested to gain a better understanding of viewstate.
May 07, 2015 09:36 AM|mgebhard|LINK
Dynamic controls, regardless of the controls type, must be loaded early on each and every page request. There is nothing in the .NET framework that remembers the intended control state. You must tell the framework what controls to recreate.
Generally, this means taking advantage of ASP state management to persist the number and types of controls dynamically created. The the Page_Init will contain logic to read the persisted state then recreate the controls. Once the controls are created,
the framework can find and bind the controls to the incoming forms collection.
I wanted to know is what happens if I drop userControl1 and on a postback load userControl2 with id="xyz2". Does the viewstate automatically drop the info for id="xyz1" (ie userControl1)? I am assuming that the viewstate is rebuilt each postback based on the
controls on the page at that time.
The form collection including ViewState is submitted as usually. The framework simply cannot find the control because the control does not exist. Static controls (markup) exist but not the dynamically created controls.