36

I have some code that essentially looks like this:

<div>
    <% if(Something) { %>
        <div id="someUniqueMarkup">
            This markup should not be output if Something==true.

            <units:MyUserControl runat="server"/>
        </div>
    <% }
    else { %>
        <units:MyUserControl runat="server" />
    <% } %>
</div>

Depending on Something, one of them is hidden, and that is fine. But if I set break points in the user control, I notice it's being loaded twice (once for each of the controls above) and all it's logic is being run twice. I could of course control this with placeholders or multiviews, but the same thing seems to apply - OnLoad/Page_Load etc is run once for each control that is actually on the page.

EDIT: The reason why im showing/hiding this is because I need to include some markup around the control if Something == true. I could wrap the "unique markup" itself in if-else before and after the control, but that just seems dirty for something that really should be as simple as I've imagined above. The user control itself should be exactly the same in both scenarios, sorry for the confusing property it had.

Is it just me, or is this just a really unintuitive interface? And is it actually possible to not load/execute a user control at all as long as it's on the page?

4

2 回答 2

53

由于您在页面上有两个控件,它将同时呈现它们。您创建的 if-check 仅确定它是否包含在输出中。防止这种情况的最简单方法是像这样更改您的代码:

<div>
    <units:MyUserControl runat="server" SomeSetting="<%= Something %>" />
</div>

编辑:回答原帖中的编辑:

<div>
    <% if(Something) { %>
        <div id="someUniqueMarkup">
            This markup should not be output if Something==true.

            <asp:placeholder id="phItemInDiv" runat="server" />
        </div>
    <% }
    else { %>
        <asp:placeholder id="phItemOutsideDiv" runat="server" />
    <% } %>
</div>



MyUserControl ctrl = (MyUserControl)LoadControl("/pathtousercontrol.ascx")
if (something){    
    phItemInDiv.Controls.Add(ctrl);
}
else{
    phItemOutsideDiv.Controls.Add(ctrl);
}

这样,如果Something为真,您将只发出(并加载)用户控件

于 2013-05-29T08:37:47.123 回答
1

在我看来,最好的方法是在 ASPX 中声明一次用户控件。

在后面的代码中,在 PageLoad 上,应用您认为合适的逻辑:

if(something)
    MyUserControl.SomeSettings = ...

如果年表出现问题,请在 PreLoad 中执行上述逻辑,因为它将在页面及其所有相关用户控件的页面加载之前触发。

编辑:

您可以在启用 = false 的用户控件上放置两个不同的 ID。在 Page_load 中,根据您想要的逻辑将 Enabled 设置为其中之一。

于 2013-05-29T08:46:01.633 回答