Label vs Literal in ASP.NET

Unlike the Label control, the Literal control does not render any additional html tags thats why the best practice says: never use the ASP.NET Label control when a Literal can do the job. In different cases we use the Literal/Label controls to label input controls without knowing the difference between them. The below should help you to decide which control you should use when building asp.net web application.

Label vs Literal:


Label:

The Label web server control is used to label other controls on an aspx web page/UserControl. It is used to display text with the ability to change the style (appearing) of the displayed text.

Inheritance Hierarchy:
System.Object
  System.Web.UI.Control
    System.Web.UI.WebControls.WebControl
      System.Web.UI.WebControls.Label

<asp:Label ID="lblFirstName" runat="server" CssClass="myCssClass" Text="First Name" />

It will be rendered as:

<span id="ctl00_ContentPlaceHolder1_lblFirstName" class="myCssClass">First Name</span>
(NB: the id of the Label is related to the structure of your asp page and if you are using MasterPage or not)
 
Literal:

Use the System.Web.UI.WebControls.Literal control to reserve a location on the Web page to display text. The Literal control is similar to the Label control, except the Literal control does not allow you to apply a style to the displayed text. You can programmatically control the text displayed in the control by setting the Text property.

Inheritance Hierarchy:
System.Object
  System.Web.UI.Control
    System.Web.UI.WebControls.Literal 

<asp:Literal id="litFirstName" runat="server" Text="First Name"/>

It will be rendered as:
 
First Name

11 Comments

Add a Comment

As it will appear on the website

Not displayed

Your website