James
James

Reputation: 7533

ASP.NET control to render a <div>

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?

Upvotes: 41

Views: 91952

Answers (6)

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64933

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>

It's a container, so you add Controls to it in the code-behind like:

myPanel.Controls.Add(new LiteralControl("Hello World"));

You can add the Literal control (or any others) in the markup if you like and just assign to its Text property if you want it to update dynamically at runtime.

Upvotes: 67

Eyad Eyadian
Eyad Eyadian

Reputation: 101

Try this:

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

Set your text inside Literal, which renders without html tag

Upvotes: 5

Jin Thakur
Jin Thakur

Reputation: 2773

div runat="server" id="myserversideDiv" 

my inner text here. It has inner text and inner html property and most of asp.net server control property. Try that.

Upvotes: 0

Pablo
Pablo

Reputation: 2271

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

Upvotes: 2

Oleks
Oleks

Reputation: 32323

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).

Upvotes: 32

Widor
Widor

Reputation: 13275

Try the Panel control.

Upvotes: 8

Related Questions