ASP.NET Show Div conditionally

I have googled this and didn't find what I needed. All the existing solutions I have found say to set visibility to false. This doesn't seem to work for me, as my application makes a PDF that just "hides" the DIV and leaves a lot of white space on it.

Instead, I would not want to render HTML at all. For example, in PHP this can be done in the same way as:

<?php if ($showDiv == true) { ?>
<div>Lorem ipsum dolor sit amet</div>
<?php } ?>

      

In ASP.NET MVC, I can just pass the ViewBag variable and do the same.

What's the solution for this in ASP.NET (C #)?

+3


source to share


6 answers


<% if ( showDiv ) { %>
<div></div>
<% } %>

      



where showDiv will be the protected property in your code.

+9


source


In the aspx file

<div runat="server" id="hideableDiv">Lorem ipsum dolor sit amet</div>

      



And in the code

...
hideableDiv.Visible = false;
...

      

+8


source


use a control <asp:panel>

that renders as HTML <div>

. Then you can toggle the visibility. If the parameter is visible

set to false, asp.net will not render any content.

    <asp:Panel id="MyPanel" runat="server">
    ...
    </asp:Panel>

   MyPanel.Visible = false;

      

+3


source


Markup

<div runat="server" id="myPdfDiv">Lorem ipsum dolor sit amet</div>

      

Code code

myPdfDiv.Visible = false;
myPdfDiv.InnerHTML = "";

      

+2


source


Yes, you can place a div inside an ASP PlaceHolder control:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.placeholder(v=vs.71).aspx

<asp:PlaceHolder id="PlaceHolder1" runat="server">
<div></div>
</asp:PlaceHolder>

      

Then in codebehind you can set it like this:

PlaceHolder1.Visible = true;

      

+2


source


Another solution that would not generate HTML:

Html

<asp:Literal ID ="litDiv" runat="server">       
</asp:Literal>

      

Code for:

bool showDiv = true;
if (showDiv)
    this.litDiv.Text = "<div>Lorem ipsum dolor sit amet</div>";

      

+2


source







All Articles