asp:Label vs asp:Literal: Best Practices

Many times we are using asp:Label controls as Label to various Input controls (Textbox, DropDown etc.) and most of the time we are not applying any styles to Label control.

 

Label vs Literal:

 

Label:

 

<asp:Label id="lblMessage" runat="server" CssClass="anyclass" Text="My Label" />

 

will be rendered as:

 

<span id="ctl00_ContentPlaceHolder1_lblMessage" class="anyclass">My Label</span> //assuming you are using masterpage

 

Literal:

 

<asp:Literal id="ltrMessage" runat="server" Text="My Literal" />

 

will be rendered as:

 

My Literal

 

In any case(with or without masterpage), extra <span> element with id is added to rendered HTML. You can see from the difference in rendering of Label and Literal control that Labels should be used only when any kind of styling needs to be applied to the Text rendered by Label. In my case, most of the time we are giving styles to the TD element and no extra styling required for Text inside TD element. In that case, you must use Literal control to minimize the amount of HTML rendered in browser.

Hope this helps...

114 Comments

Comments have been disabled for this content.