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.
August 10, 2007 at 7:42 am
[...] Brian Webster’s Blog Web Development and Other Ramblings « asp:label or asp:literal [...]