ASP.Net: User controls added to placeholder dynamically cannot retrieve values

前端 未结 8 1743
攒了一身酷
攒了一身酷 2021-02-09 02:53

I am adding some user controls dynamically to a PlaceHolder server control. My user control consists of some labels and some textbox controls.

When I submit the form

相关标签:
8条回答
  • 2021-02-09 03:32

    As others have said, any form of control manipulation must be done before viewstate is created.

    Here is a good link on the page lifecycle to help you out:

    http://msdn.microsoft.com/en-us/library/ms178472.aspx

    0 讨论(0)
  • 2021-02-09 03:34

    This is based on .NET v1 event sequence, but it should give you the idea:

    • Initialize (Init event)
    • Begin Tracking View State (checks if postback)
      • Load View State (if postback)
      • Load Postback Data (if postback)
    • Load (Load event)
      • Raise Changed Events (if postback)
      • Raise Postback Events (if postback)
    • PreRender (PreRender event)
    • Save View State
    • Render
    • Unload (Unload event)
    • Dispose

    As you can see, the loading of ViewState data back to the controls happen before the Load event. So in order for your dynamically-added controls to "retain" those values, they have to be present for the ASP.NET page to reload the values in the first place. You would have to re-create those controls at the Init stage, before Load View State occurs.

    0 讨论(0)
  • 2021-02-09 03:34

    I also want to add that I've seen user controls work the way that you'd expect them to just by setting the Control.ID property at run time. If you do not set the ID, items may get built in a different order and work oddly.

    0 讨论(0)
  • 2021-02-09 03:37

    I believe you'll need to add the UserControl to the PlaceHolder during the Init phase of the page life cycle, in order to get the ViewState to be filled in by the Load phase to read those values. Is this the order in which you're loading those?

    0 讨论(0)
  • 2021-02-09 03:41

    We have experienced the same thing and have handled it by using ghost controls on page_load that have the exact same .ID and then the post back picks up the events and the data. As others said it's the dynamic adding of the control after the init stages that the state is built already and controls added after aren't stored.

    Hope this helps a bit.

    0 讨论(0)
  • 2021-02-09 03:43

    You have to create your controls in the Page_PreInit event handler. The ASP.NET server control model is tricky; you have to fully understand the page lifecycle to do it right.

    0 讨论(0)
提交回复
热议问题