Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c# - If statements in aspx files

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you have two controls on the page it will render them both. The if-check you create, only determines whether it's included in the output. The easiest way to prevent this is to change your code like this:

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

EDIT: Answer to edit in the original post:

<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);
}

This way you will only have the user control emitted (and loaded) if Something is true


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...