ASP.NET control to render a <div>

83,369

Solution 1

I think you need HtmlGenericControl class. It has a constructor which accepts a string variable which initializes a new instance of the HtmlGenericControl class with the specified tag:

var div = new HtmlGenericControl("div");

It is also has InnerHtml and InnerText properties (you mentioned this in a comment to the previous answer).

Solution 2

Of course: ASP.NET has a built-in control called Panel!

And you may use it as follows:

<asp:Panel ID="myPanel" runat="server">
    <!-- Other markup here like client and server controls/elements -->
</asp:Panel>

Solution 3

Try the Panel control.

Solution 4

Try this:

<div class="myclass">
<asp:Literal ID="mytext" runat="server"></asp:Literal>
</div>

Set your text inside Literal, which renders without html tag

Solution 5

<asp:Panel>
<div id="NoRecords" runat="server" visible="false">No records are available.</div>
</asp:Panel>

Code-Behind

 protected void MyRepeater1_PreRender(object sender, EventArgs e)
{
    if (MyRepeater1.Items.Count == 0)
    {
        NoRecords.Visible = true;
    }
    else
    {
        NoRecords.Visible = false;
    }
}
Share:
83,369
James
Author by

James

Assistant Headteacher at a UK secondary school Creator of MiniTest, an app for online marking and feedback

Updated on December 09, 2020

Comments

  • James
    James over 3 years

    The Label control in ASP.NET seems to render <span> tags, but is there a server control to render HTML within a <div>?

    Sure, I could set display: block and it might look the same, but I'd rather not be nesting divs inside spans. Also I'd prefer not to use <%= MyVariable %> because that might not behave nicely on postbacks.

    Any suggestions, please?

  • James
    James about 13 years
    Thanks. Could I put this directly in the page markup, or does it have to be added to a Panel?
  • Oleks
    Oleks about 13 years
    You could use it in markup like: <div runat="server" id="myPerfectDiv">my inner text here</div>
  • James
    James about 13 years
    Cool. What's the difference between the InnerText and InnerHtml properties? Should I just use InnerHtml?
  • Oleks
    Oleks about 13 years
    InnerText property provides automatic HTML encoding/decoding. See: e.g., if the InnerText property is set to <b> Hello </b>, the < and > symbols are converted to &lt; and &gt;, respectively. Fot the InnerHtml property the rendered output would be: <b> Hello </b>.
  • Mircea Ion
    Mircea Ion about 11 years
    If I would decide to use Panel how will I add new HTML element attributes like ones for which Panel doesn't have a corresponding property?
  • Matías Fidemraizer
    Matías Fidemraizer about 11 years
    @MirceaIon As any other WebControl, you've the Attributes property: msdn.microsoft.com/en-us/library/…