Reputation: 4020
I have a piece of code in an ASPX file like this:
<% if(!string.IsNullOrEmpty(Session["MySessionVar"] as string)) { %>
<td valign="top" style="width: 300px; height:20px;">
<uc:MyUserControl ID="myUserControl" runat="server" />
</td>
<% } %>
The point of this code is that if the session variable doesn't exist, or is empty, then the user control will not load onto the page.
However, I found that no matter the value (or non-value) of the session variable, the user control still attempts to load itself (it invokes the Page_Load which throws an error because the session variable value is null or empty).
I verified that the 'if' statement logic is correct by replacing the user control HTML code with a script tag to present an 'alert' dialog to the user. I found that that the alert box correctly appeared only when the session variable existed and wasn't empty.
It seems that when the session variable does exist (and isn't empty), the User Control will appear on the page. But when the session variable doesn't exist (or is empty), the User Control will not appear on the page... but the Page_Load event will still be invoked?
Why is that, and how do I stop it from being invoked?
Thanks
Upvotes: 0
Views: 98
Reputation: 2793
The if
server tag determines whether or not the section would be included in output, but this part is decided later in the Page
lif cycle (PageRender
). But the load
event for the Page
as well as the user control fires before that. That is why Page_Load
event of your user control is still firing.
Now for your problem, ideally you should check the Session for null in the user control itself.
Hope this helps.
Upvotes: 2