Asp.net: conditional loading of user controls fails

Hi (sorry for the bad title)

I have a user control that loads various additional user controls based on conditions such as 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 right; expected content is displayed. But I noticed that even if someValue! = 1 is displayed and control B, control A is still loading backstage (page loading is called).

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

+6
source share
3 answers

Page_Load is called because you are handling this event. Do not try to load them this way, but instead use Visible-Property instead of codebehind.

Output a public function that the controller (in your case, SubPage.ascx ) calls after it has changed the visible state to load the contents of UserControl. Controls that do not display will not display as html at all.

Loading controls dynamically, if you really don't need it, can cause unnecessary problems with ViewState or Event-Handling. Here are some other disadvantages associated with dynamic UserControls.

+2
source

Instead, you need to call the LoadControl method

 <% if (someValue == 1) { %> Loading user control A.. Page.LoadControl(("~\ExampleUserControl_A.ascx"); <% } else { %> Loading user control B.. this.LoadControl(("~\ExampleUserControl_B.ascx"); <% } %> 
+2
source

Code Front:

 <%@ 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" %> <asp:placeholder id="plhControls" runat="server" /> 

Code for:

 if (someValue == 1) { CTRLA ctrlA = (CTRLA)LoadControl("~/Controls/ctrlA.ascx"); plhControls.Controls.Add(ctrlA); } else { CTRLB ctrlB = (CTRLB)LoadControl("~/Controls/ctrlB.ascx"); plhControls.Controls.Add(ctrlB); } 
0
source

Source: https://habr.com/ru/post/886964/


All Articles