ASP.Net: Literal vs Label

When you have code similar to

<asp:Label EnableViewState="false" ID="Label8" runat="server" 
        AssociatedControlID="txtEmail">Email Address:</asp:Label>

<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

It is optimal to use a label element because it will correctly turn it into a html label element with the correct for attribute targeting your text box, so that if a user clicks on the label it automatically sets their cursor inside the text field.

Otherwise use the literal unless having the text wrapped in a span would be beneficial for css styling.


enter image description here

To display simple text, formatted text or HTML text as it is i will start with literal first as its lightweight and does not emit out extra SPAN tags.

See this video which demonstrates about those extra tags.

But we can not apply CSS on a literal , we can not add attributes like Label1.Attributes.Add to a literal. Any container oriented things can not be achieved as literal is not surrounded by a SPAN tag.

It's also sad to see lot of ASP.NET Webform guys by default choose label to display text not knowing that it generates extra SPAN tags which can make your HTML heavy if you have lot's of label.


Yep, the main difference is that Literal controls just render out text, but Label controls surround it with <span> tags (Unless you use the AssociatedControlID property, in which case a Label control will render a <label> tag).

So, labels can be styled easier, but if you're just inserting text, literals are the way to go. Literal controls also have a handy property Mode which governs how the text is rendered. You can have it HTML-encoded, or rendered without any changes, or have any "unsupported markup-language elements" removed.

If you're not applying any styles (e.g. by using Label's CssClass property), it will be fine to replace Label controls with Literal controls.