Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net: conditional loading of user controls fails

Hello (sorry for the poor title)

I have a user control which loads different additional user controls based on some conditions like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SubPage.ascx.cs" Inherits="SubPage" %>
<%@ Register Src="<srcA>" TagName="A" TagPrefix="CTRL" %>
<%@ Register Src=">srcB>" TagName="B" TagPrefix="CTRL" %>

<% if (someValue == 1) { %>
    Loading user control A..
    <CTRL:A runat="server" />
<% } else { %>
    Loading user control B..
    <CTRL:B runat="server" />
<% } %>

The result will look correct; the expected content is displayed. But I noticed that even though someValue != 1 and control B is displayed, control A is still loaded behind the scenes (page load is called).

Why is this? And what would be a better approach? Thanks.

like image 414
OlavJ Avatar asked Apr 29 '11 13:04

OlavJ


2 Answers

Page_Load is called because you handle this event. Don't try to load them in this way but use the Visible-Property instead from codebehind.

Expose a public function that the controller(in your case SubPage.ascx) calls after it changed the visible state to load the content of the UserControl. Controls that aren't visible won't be rendered as html at all.

Loading controls dynamically if you don't really need can cause unnecessary ViewState- or Event-Handling issues. Here are some other disadvantages mentioned regarding dynamic UserControls.

like image 179
Tim Schmelter Avatar answered Nov 01 '22 22:11

Tim Schmelter


You need to call LoadControl method instead

<% if (someValue == 1) { %>
Loading user control A..  

Page.LoadControl(("~\ExampleUserControl_A.ascx");

<% } else { %>
    Loading user control B..
    this.LoadControl(("~\ExampleUserControl_B.ascx");
<% } %>
like image 35
Muhammad Akhtar Avatar answered Nov 01 '22 22:11

Muhammad Akhtar