问题
Here is what I am trying to do. I have a page with two link buttons and an updatepanel (the two linkbuttons trigger the updatepanel). I have two usercontrols which have labels with same ID's. When I click the first link button, I add the first usercontrol to the updatepanel and set the label value to datetime.now
when i click the second link button i add the second usercontrol but i see that the value of the label from the first control is set in the label in second user control. if the id's are different there is no problem - but in my case the usercontrols are being developed by different teams and I am integrating them in the way i mentioned - so they may have same ids.
i have browsed all over and tried various suggestions but i cannot get this to work, any help will be greatly appreciated.
Thanks
Job Samuel
回答1:
Your problem has nothing to do with the UpdatePanel, actually.
Imagine what would happen if you had a 3rd LinkButton, which did nothing but postback. What would happen if you clicked the 1st LinkButton, the UserControl appeared, and then you clicked the 3rd one? What do you expect to see? If you think you will see the UserControl again, you are wrong. Dynamically created controls must be created every request, they don't stick around automatically. ViewState remembers the state of controls on the page, NOT what the controls themselves are in the first place -- thats what the markup in the aspx page does. Dynamically created controls obviously arent in the markup, so they arent automatically recreated.
You need to think of the lifecycle of a control as 'straddling' half way between two requests. It starts half way into one request and ends half way into the next. You need to save which user control is currently displayed in either a hidden field or a Page.ViewState value (not the user control itself mind you, just whatever information you need to figure it out), then reload that control from the page's OnLoad. If you do that -- the sequence will go like this:
(1) Click LinkButton1 (2) UserControl1 dynamically created (3) Click LinkButton2 (4) Page.OnLoad reloads UserControl1 (5) UserControl1 loads its postback data and viewstate (6) LinkButton2's click event fires (7) Remove existing UserControl1 and add UserControl2 dynamically (8) UserControl2 can have the same ID, since UserControl1 already 'consumed' its state.
I suggest you browse my series of articles on Understanding Dynamic Controls in ASP.NET: http://weblogs.asp.net/infinitiesloop/
回答2:
You have to set a different id for the label when you create the user control.
来源:https://stackoverflow.com/questions/2214023/wrong-state-in-server-controls-with-same-ids-when-dynamically-adding-usercontro