It's the Name, Stupid!

time to read 3 min | 553 words

It's one of those situations, where the very fabric of reality itself is wrapped. I'm feeling smart, because a prediction of mine (see the footnotes) came true, but my prediction was that I would feel like an idiot. I compromise by feeling stupid. I've wasted days trying to find out a problem in one of my ASP.Net pages. I just found it, and it was in a moment of enlightenment: "Oh, so that was it?"

I'm going to go over the scenario, so you can appreciate just how stupid the whole thing was:

·         The page has user control that is being loaded dynamically. The choice of which user control to display is controlled via a drop down list.

·         On the OnInit Event, I create the current control, and add it to the page.

·         The page has also grid view that display a list of rules

·         .When a row in the grid view is selected, a user control is created and added to the page (the previous control is removed), and the current control value is set to the new value.

·         The problem occurred only when updating information (a row was selected, the UI displayed correctly, but when posting back, the values were never there.).

If you're an ASP.Net guru, you may have already realized where I did wrong. If you're not a guru, let me give you a brief overview of what was happening, one step at the time:

  The user select a row, the page is post back with the new value.

  The OnInit method is executed and the user control X is added to the page. It gets a default name of c00.

  ViewState magic happens.

  The select event handler for the gird view is run, and the first user control is removed, and user control Y is added. It gets a default name of c01.

  The page is sent to the user, who update the page and save.

  The OnInit method is executed and the user control Y is added to the page. It gets a default name c00.

  The postback data for the control had the ID of c01, and there is no such control in the page now.

  The view state contains data belonging to control with id c00, which exist on the page.

  Ayende go raving mad trying to find why the control doesn't get the proper values.

No wonder that I couldn't reproduce the problem. It has to happen in exactly the right way for it to appear. The solution to it was to add one line to the base user control constructor, giving it a fixed name.