Search code examples
asp.netpageloadserver-tags

PageLoad and OnPreRender invoked on controls that should not be rendered


I'm using this oversimplified code block:

<% if (MyCondition())
{ %>
<myUsedControl/>
<% }
else
{ %>
<myUnusedControl/>
<% } %>

in my ascx file. I assumed that when ASP.Net would read this page, if MyCondition() returned true, it would completely ignore whatever was in the else clause. This is not the case, the myUnusedControl's PageLoad and OnPreRendered events are still being fired when I load the page, even though myUnusedControl is properly hidden when the browser displays the page.

Why is this? How can I make sure a chunk of ascx or aspx be completely ignored when a page is rendered?

Thanks for your time.


Solution

  • You could always create a duplicate page with the 2nd control and put your if condition branching earlier in the pipeline to control which page gets loaded.

    For this example, you could always add the control manually to the controls collection in the code behind and do your branching around that rather than registering the control in the ascx/aspx page markup.