The secret of ViewStateModeById

time to read 2 min | 230 words

I recently had a problem in ASP.Net that was certain to put me in an asylum. Here is the story:

I've a page that loads controls dynamically. On postback, the page would replace the dynamic control with a different one. Both controls had a drop down list, each with its own ID, each with its own values.

The problem that I had was that for some unknown reason, the values from the first list were copied to the second list. I had no idea what was happening, and I was one step away from finding just how strong the walls are*.

Eventually a friend found out the answer. Apparently ASP.Net 2.0 uses indexes instead of IDs to figure out which view state belongs to which control. By some freak accident, I managed to stumble on the one occasion where this would be a problem. The solution to the problem? Just decorate the controls you're loading with ViewStateModeById, and you're done.

One thing that I noticed is that it's not possible to mix & match controls with this attribute and controls without it. I get view state exception when I try to do that. It doesn't bother me one bit, since the exception at least remind me that I need the attribute, and that would save a bug to fix later.

 

* For instance, are they stronger then my head?