Recently at work I encountered severe problems with the ASP.net viewstate. We have build a very nice framework which we
use on our web projects for dynamically adding validation controls to our text-fields or dropdown lists on the UI
according to the validity of rules defined in the business logic. Moreover we make use of the .NET's new
AjaxControlToolkit's UpdatePanel (I'll come to that back in a later post since that's another story).
after a postback suddently all of my dropdown lists were empty. My first assumption was immediately that there must be
something wrong with the viewstate especially because often it happened after the first and often only after the second
postback. I'm not yet an expert in ASP.net since I'm now working for approximately 2 months with it but as far as I
know, the viewstate is stored in some obscure way according to an index which corresponds to the position of the
control on the UI. So that position could have been changed due to the adding of new controls dynamically after the
postback. Actually that was the case. The strange thing is just that all of the newly added controls had their
"EnableViewstate" property set to false. Shouldn't it then be ignored by the viewstate?? Apparently it isn't. Anyway,
trying to this I set the [ViewStateModeById] attribute on the UserControl's code:
partial class MyUserControl : UserControl
setting this property, the control's direct
children are managed in the
viewstate by using their ID instead of the index. This attribute can be applied to basically all containers. After that
change, 3 out of the 4 dropdown lists worked and 1 didn't...damn :( .
So the final approach was to change our
framework such that ALL of our validator controls are added immediately, handling their IsValid
property depending on the outcome of the rules. In that way no controls were added dynamically...and look at that,
everything worked out fine, no more problems of empty dropdown lists or broken viewstate.
The résumé: if you're
experiencing similar problems, check whether you add new controls dynamically. Your problem might be there.
one would have to do is to further research how the viewstate is managed by the ASP.net framework in order to
understand these things in deep. My assumption is that there is some kind of tree-like structure (i.e. a binary tree or
so ??) which is mapped to the controls present on the page after the postback. If there are a lot of changes, whole
subtrees may be discarded wherefore 1 of my dropdowns wasn't loaded correctly also after I changed to the ViewStateModeById
If you have any further informations you're invited to leave a comment :)
Questions? Thoughts? Hit me up on Twitter