asp.netpostbackviewstate

Clearing then re-creating controls will result in different dynamic IDs in ASP.NET


This may be a silly situation and a bit of a lengthy read, but I hope someone may have some tips regarding my issue.

Long story short, I have a situation where I am storing a decision-tree like data in JSON format in a ViewState field, and I dynamically generate Buttons to allow the users to edit this decision-tree (add/change/remove steps, etc).

Everything is mostly fine, but upon PostBacks I have an issue where the dynamic ID of the generated Buttons changes. The reason for that is the life cycle and that way the Buttons get generated twice. The life cycle goes as this:

So the problem seems to stem from the fact that PageLoad happens before the Button event handler, so I have to render the Buttons twice when making manipulations. PageLoad does it automatically, then Button event changes the data, so need to re-render the Buttons to show the changes. But the system seems to remember the IDs generated on PageLoad. When re-rendering the tree, my goal would be to completely clear the IDs generated on PageLoad, so when I re-render in the Button click event, they are the same as the PageLoad generated IDs.

So far I tried simply with Controls.Clear() or Control.Dispose(), but neither of them seemed to work. While the control visibly disappears, the ID must remain stored somewhere, because the newly generated IDs will be different.

So for example how do I dispose of MainContent$ctl02, so when I create a new Button, it will be once again called MainContent$ctl02?


Solution

  • Okay, after further attempts, I seemed to have solved the issue by using ClienIDMode.Static on each generated Buttons and setting the IDs myself (using the path of the JSON nodes of the steps as ID).

    Hopefully this will work in the long run.

    But I still wonder if the original issue can be prevented somehow?