Dynamically Create controls and save the controls values across postback - ASP.Net C#

筅森魡賤 提交于 2019-12-12 11:09:35

问题


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 -

  1. Tab Title
  2. Tab Content
  3. 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 -

  1. 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.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!