ASP.NET Literal vs Label

Home Articles Downloads Links About

Summary


The following article describes some details of the Web controls Literal and Label. And under what circumstances it is recommended to use each of them.

The Literal Control


Literal control is used to display static text on the Web page. The Literal inherits from class Control. When the Literal is rendered to HTML it does not add any HTML tags. Therefore, it does not have a Style property and cannot get any styles. 

For example, the following literal control with setting the Text property in the code behind::

<asp:Literal ID="lTest1" runat="server" Text="Test Literal" />

protected void Page_Load(object sender, EventArgs e){
  lTest1.Text = @"<font size=8>" + lTest1.Text + "</font><script>alert('Hi Literal');</script>";

}

Is rendered at the Client as:
<font size=8>Test Literal</font><script>alert('Hi Literal');</script>

The Label Control


The Label control is similar to Literal, as both are used to display text. The Label control, as most web controls, inherit from WebControl. The Label is rendered as <span> tag. But you can set html tags and JavaScript in the text property.

For example:
The following label and code behind:

<asp:Label ID="lbTest1" runat="server" Text="Test Label"/>

protected void Page_Load(object sender, EventArgs e){
  
lbTest1.Text = @"<font size=7>" + lbTest1.Text + "</font><script>alert('Hi Label'); </script>"; 

}

Is rendered as:

<span id="lbTest1"><font size=7>Test Label</font><script>alert('Hi Label');</script></span>

Literal Vs Label


It’s recommended to use the Label control when server code changes the text or the properties.
Also Label control can be used as the caption of the TextBox or other controls in situation where using the access key for the Label moves the focus to the control to the right of the label.
Literal can be used when you want to render static text, HTML and controls directly to the page without getting any additional HTML tags.

Important considerations:
Both Label and Literal are vulnerable to Cross Site Scripting (XSS). Therefore, if the text property of the Literal is populated from not trusted source it could be set the Mode property to Encode (The property Mode specifies how it is handled the content of the Text property). This will provide HTML encoding of the data into the Text property.  

For example:

<asp:Literal ID="lTest1" runat="server" Mode="Encode" Text="Test Literal" />

protected void Page_Load(object sender, EventArgs e){
  lTest1.Text = @"<font size=8>" + lTest1.Text + "</font><script>alert('Hi Literal');</script>";

}

It is rendered as:

&lt;font size=8&gt;Test Literal&lt;/font&gt;&lt;script&gt;alert('Hi Literal');&lt;/script&gt;

The Label does not has Mode property therefore it could be used HttpUtility.HtmlEncode of Server.HtmlEncode to encode the data.


Google Ads