Improve your code: ASP.Net Label vs Literal

4:26 pm Improve Your Code

Questions:

  • Do you know what is the difference between an asp:Label and an asp:Literal?
  • Do you know when to use one and when to use the other?

If you do, don’t read, if you don’t keep on reading:

Differences:

Label:

ASP.Net:

<asp:Label ID="messageText" runat="server" meta:resourcekey="messageTextResource1" />

Rendered HTML:

<span id="ctl00_Main_ctl00_messageText">An email has been sent to 'gigi@gigi.com'.  </span>

Literal

ASP.Net:

<asp:Literal ID="messageText" runat="server" meta:resourcekey="messageTextResource1" />

Rendered HTML:

An email has been sent to 'gigi@gigi.com'.

As you can see an asp:Literal does not generate a <span> tag. This is the main difference.

Real life scenario:

When you embed a tag into another tag you should be aware of the validity of the generated code. I know most of us don’t (yet) target to generate any valid XHTML code it would be nice to get this first time around, so writing correct code in the first place should be important for us.

If you have the following pattern:

ASP.Net:

<h2><asp:Label ID="lblSomeTitle" runat="server" meta:resourcekey="lblSomeTitleResource1"></asp:Label></h2>

Rendered HTML:

<H2><span id=” ctl00_Main_ctl00_lblSomeTitle>Step 2 of 3</span></h2>

This is invalid HTML as per XHTML 1.0 Strict or XHTML 1.1 Strict.

Not only we generate too much code (we have an extra Span with an id for no valid reason) we are also breaking standards. IE6, IE7 accepts it, FF mostly accepts it but it’s wrong.

The fix is simple: Change your code to use a Literal

ASP.Net:

<h2><asp:Literal ID="lblSomeTitle" runat="server" meta:resourcekey="lblSomeTitleResource1"></asp:Literal></h2>

HTML:

<H2>Step 2 of 3</h2>

Almost the same code, much better and smaller HTML.

When to use which:

  1. Use Labels when you need to set a CSS class (errors or so)
  2. Use Labels when you have references from JavaScript to your label.
  3. Use Labels when they represent Field set labels with an AssociatedControlID set
  4. Use Literal when you need to display data that the user has originally entered (names, emails…) and set the Mode=”Encode” attribute to automatically Html Encode the rendered data to help avoiding CSS injection attacks
    • An even better approach is to use the AntiXSS library and encode your un-trusted strings before setting them into the label/literal.
  5. Use Literal in every other scenario

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.