Panel and User Controls vs load User Controls dyna

2019-07-03 04:36发布

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条回答
再贱就再见
2楼-- · 2019-07-03 05:33

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)!
查看更多
登录 后发表回答