3

What is the difference between the asp:label and the html label ?

I know that the first one is rendered on the server so basically it returns a span tab, but what is its use? What are the cases in which one would want to use a HTML tag and in what would one want to use the asp:label? I know that if I put it as an ASP control I can programatically access it, but what are differences between the 2 purely in terms of designing the UI?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user590849
  • 11,655
  • 27
  • 84
  • 125
  • 2
    A good post to imagine the difference [http://stackoverflow.com/questions/6839007/should-i-use-the-asplabel-tag][1] [1]: http://stackoverflow.com/questions/6839007/should-i-use-the-asplabel-tag – Muhammad Hani Jan 12 '13 at 20:27
  • An asp:label gets rendered as a label if has an AssociatedControlID – ScottE Jan 12 '13 at 20:58

1 Answers1

9

If the asp:Label has its "AssociatedControlID" attribute value set to the ID of form control on the page then it will actually be rendered as a HTML label control (with the "for" value set to the client ID of the same control) when rendered to the client.

The HTML label control is designed strictly to provide a label/caption for a form control (i.e. an input, select or textarea) which describes the purpose of the form control to the user (see https://developer.mozilla.org/en-US/docs/HTML/Element/label). The label is normally (strongly) associated with the particular input using the "for" attribute which should be the ID of the input. This is particularly useful for those with accessibility needs who are not able to interpret the relationship based solely on proximity of the text and control. Imagine a form with several textboxes but no way to know which input was required in each one. The HTML label control is not used for general text outside of this context.

If the "AssociatedControlID" attribute of the asp:Label has no value then the control will simply be rendered as a span control containing the text. Some developers like to use asp:Labels to output text onto the page, giving the control a dual purpose (unlike the HTML counterpart). I personally prefer to use asp:Literals for this purpose as it gives me more control of the containing markup.

The reason to choose the asp:Label as opposed to the native HTML label control is that you can easily interact with it using server side code, for example changing the text or CssClasses in response to server events, and you can enter the server ID as the "AssociatedControlID" value which will automatically be rendered as the client ID (e.g. shown as "ct100_MainContent_TextBox1" as opposed to "TextBox1") in the "for" value on the client.

pwdst
  • 13,909
  • 3
  • 34
  • 50