问题
Consider this -
I allow the end user to create a tab control dynamically in an ASP.Net page by getting some details. For each and every tab added I get some settings -
- Tab Title
- Tab Content
- Tab Footer link
So I get these details for each and every tab. The user is provided with a button 'Add Tab' to more one more tab. So I need to add one more tab settings panel in the page to get the tab settings. But doing so, I lose the values entered in the previously created dynamic tab settings panel. The user can add as many tabs and enter settings for each and every tab. Finally when they save it I build the tab control (based on their settings and content) and I render the control.
Since the controls are dynamic, I'm able to thing of two options -
- Recreate previously created n - 1 tab settings panel while adding a nth tab. So across each and every postback I need to recreate the settings panel for each and every tab. But I don't know how to persist the values in this case.
- Add the settings panel in the client side with simple html controls and on page UnLoad parse the controls -> Parse the settings -> Save it in a hidden field -> Get it in the server side. In this case I lose all the server side capabilities where I need to write validation scripts for the controls.
Any insights on how better to do this?
回答1:
I would add the controls server-side, just remember that you need to re-create all controls on every postback
You could save your details of any controls that need to be created in viewstate then build your control tree from that in CreateChildControls
回答2:
One method is to save data that you need to recreate the tabs in the ViewState. You can do this during the PreRender event for example. On Postback you need to recreate the controls you had originally, maintaining their original IDs and their order in the hierarchy. You can do this during the LoadViewState phase.
Once in Page_Load you can create your new tab
回答3:
I've implemented option #1 in the past. You'll have to recreate your controls tree at a certain point in page events lifecicle, so that when view event to restore viewstate kicks in, it has all the controls it needs. As far as I remember, you also need to restore all the controls in exactly same hierarchy ans with identical names it existed when page was rendered and view stated persisted, prior to be sent to the client. If there's any discrepancy, loading viewstate will not work for dynamic controls.
来源:https://stackoverflow.com/questions/5432413/dynamically-create-controls-and-save-the-controls-values-across-postback-asp-n