Label vs Literal - High-Flying C# Coding Tips


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

Label vs Literal

Here we will look at a key issue which distinguishes the ASP.NET Label and the ASP.NET Literal Web Controls.

Both the Label and Literal allow you to specify some text which appears on a web page.  This is set through the contols' Text property.  You might use a Label or Literal to dynamically put some text onto a webpage, for example when a user logs in, you display the user's name using the Label or Literal control.

However, the Label works differently to the Literal in that the Label wraps your text with a HTML <span> tag, which may be required, depending on your circumstances.  If you're just wanting your text to appear as clean HTML, with no unwanted extra HTML <span> tags wrapped around your text, then use a Literal.

The following example demonstrates how the Label control provides a <span> tag to wrap your text, and also demonstrates how the Literal doesn't provide the <span> tags.  If you don't require the <span> for some other purpose, and you don't need some of the additional Label properties, then you should use the Literal control to display your text so that your HTML is cleaner.


protected void Page_Load(object sender, EventArgs e)
{
    // bind our label and literal with some text
    labelDemo.Text = "This is the text of a label";

    literalDemo.Text = "This is the text of a literal";
}


Attaching the above code to the following ASPX code:


<asp:Label ID="labelDemo" runat="server"></asp:Label>

<br />

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


Using the 2 code examples above together produces the following HTML output:


<span id="labelDemo">This is the text of a label</span>

<br />

This is the text of a literal


So, as you can see the Label has output a <span> tag, which in many cases is unused, and therefore we are better off using the Literal.  The Label comes with additional properties over the Literal which you may find useful, however, if you're just specifying text to be displayed, and you don't require the <span> tag, then the Literal is recommended.

One final point, if you're not using the Label or Literal to display dynamic text but you're using them to display text which never changes, then performance wise it is better to put the text straight into the HTML and save some processor resources from having to construct the Label/Literal controls on the server.