Panel and User Controls vs load User Controls dynamically

半腔热情 提交于 2019-12-12 14:01:47

问题


If I want to dynamically show or hide several User Controls. Would it be better to use Panels that load the User Controls and then show or hide the Panels (visible=true/false) or would it be better to use a PlaceHolder and load (add) or unlaod(clear) them at runtime (LoadControl())?

a) I have a page that uses AJAX UpdatePanel. The page has 10 Panels, each Panel loads a User Control. In code behind I make the a Panel visible or invisible, only show one at a time. This solution is simple, as all the User Controls are in the page, it's easy to refer to them and their internal controls.

b) Loading controls dynamically using LoadControl seems a bit more complicated.

I wonder if there are any benefits compared to the method a. ViewState issues? Render performance issues? HTML size issues?

Thank you,

A


回答1:


I would prefer option A. Loading controls dynamically and recreate them in postbacks is always much more complicated and error-prone than switching the visibility of controls in aspx-markup.

I must admit that i don't understand why you are making a difference between a Panel and a Placeholder. The major difference is only that a Panel is rendered as a DIV and a PlaceHolder has no html at all.

You should lazy-load your UserControls if you have them all in page but only single UserControls visible. That means:

Do nothing in the UserControl's Page_Load but only when the controller(page) makes it visible. Therefore expose functions to load their data and update their inner UpdatePanels in the ascx. Then - after the function was called from the page and the control was made visible - let the page update the outer UpdatePanel around the UserControl.

On this way the usercontrols will neither be rendered nor databound before they have been made visible and you can always simply reference them directly.

Let them communicate in the following ways:

  • Page > UserControl via Functions/Properties
  • UserControl > Page via Events

Conclusion:

  • There are no advantages on option B neither in ViewState nor HTML-Size. Create controls dynamically only if you really need(dynamic content)!


来源:https://stackoverflow.com/questions/5587654/panel-and-user-controls-vs-load-user-controls-dynamically

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