Question

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.

Was it helpful?

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.

OTHER TIPS

ASP.NET cant deduce that MyCondition() does not depend on the execution of a subscribed PreRender event. There's also the possibility that the method has side effects that shouldn't be executed twice, so it should only be called once, and as late as possible. There's also a requirement to keep all controls up-to-date in the event cycle; how should the different components in your page work when one is not yet initialized, while others have already triggered their postback events?

In a somewhat contrived example:

Boolean _condition;
Boolean MyCondition() {
    return _condition;
}

void MyContrivedPreRender(Object sender, EventArgs e) {
    _condition = true;
}

<% if(MyCondition()) { %>
    <asp:Literal runat="server" Text="Hello world?"
                 OnPreRender="MyContrivedPreRender" />
<% } %>

Dynamically Load your control based on your conditions (LoadControl) in the Page OnInit and use that control variable in the methods you need.

public class MyClass { MyUserControl _controlVariable ;

protected override void OnInit(EventArgs e)
{
     if (MyCondition())  
     { 
          _controlVariable  = Loadcontrol("control1.ascx");
     }

     else  
     { 
         _controlVariable  = Loadcontrol("control2.ascx");

     }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top