asp:label or asp:literal

One of the issues I hear raised with ASP.NET is that it doesn’t produce valid XHTML code. In some cases, it is true that it’s hard, if not impossible, to do so. In other cases, there are simple things we can do that greatly improve the quality of HTML code from our applications. One of the easiest things is to follow the advice of Phil Haack in “ASP.NET Tip – Use the Label Control Correctly” when he says “Never use the ASP.NET label control when a Literal would do.

Consider the following lines of ASP.NET Code:

<p><asp:Label ID="lblTest" runat="server">This is a label</asp:Label></p>
<p><asp:Literal ID="litTest" runat="server">This is a literal</asp:Literal></p>

This produces the HTML code:

<p><span id="ctl00_ContentPlaceHolder1_lblTest">This is a label</span></p>
<p>This is a literal</p>

The <asp:Label> tag produced an extra <span> tag while the <asp:Literal> tag did not. This is the only real difference when the tags are used in this way. You can easily interact with either of these tags in the code behind file to assign additional, or completely different, text to the tags, so in that respect, they are completely interchangeable.

Whenever I modify an existing page that uses <asp:Label> tags, I evaluate whether to change them to <asp:Literal>. In most cases, it only takes a few minutes to make this change. When doing new pages, I always use choose <asp:Literal> over <asp:Label> whenever it will work. In doing so, the application outputs cleaner HTML.

[Updated (Dec 18, 2008): Added link to When to use asp:Label ]


3 comments so far

  1. […] Brian Webster’s Blog Web Development and Other Ramblings « asp:label or asp:literal […]

  2. tejas on

    sorry i am writing again coz it seems the html code i written is been ommitted.

    Using asp:label it generates span, is it possible to have html label generated on browser?

  3. Brian Webster on


    Sure. If you include the attribute AssociatedControlID in your tag, it will generate an HTML tag for that control, rather than the tag. In my opinion, this is the proper use of asp:Label.

    See When to use asp:Label


Comments are closed.

%d bloggers like this: