Saturday, October 3, 2015

The Proper Use Of The ASP.NET Label Control

ASP.NET Label controls are not quite the same as their WinForms counterparts. Sure, if you want to just display text on your ASP.NET form page, you COULD do the WinForms thing by placing a Label control and assigning it a text value; but that is NOT what ASP.NET label controls are actually for, and there is a better approach.

The ASP.NET Label control is actually meant for defining HTML elements. consider the following:
Above is a typical use of an HTML label. In this case, it is providing an HTML definition for an element through the use of its "for" attribute that is assigned to the input id "userName".
Creating this HTML with ASP.NET is the true intention of the ASP.NET Label control. Now lets look at how to do it:

This will produce similar HTML as in the first example. The Label control's "AssociatedControlID" generates the "for" HTML attribute; but with all the proper ASP.NET ID munging required to make the HTML work.

So what's the "correct" way to just display text using ASP.NET controls?

Remember that you only NEED to use ASP.NET controls at all if they are going to be manipulated by server-side code. For example, if you aren't displaying data-bound text, just throw that text inside a span tag on your page. But, the best way to display server-manipulated text on an ASP.NET page is to use a Literal control. The following is a snippet from inside a data-bound control:
Since I am not including an ID attribute, the resulting HTML will simply be a data-bound decimal value rounded to 2 decimal places. If I HAD included an ID, then the result would be nestled inside a span tag with a corresponding munged ASP.NET ID.

So remember, kids: ASP.NET Labels are for creating HTML text-based relationships for your ASP.NET controls and Literals should be used when you merely need to display some text that has been generated server-side.

UPDATE: There are some caveats to attempting to completely replace all of your unassigned Label controls with Literal controls. One that has stood out for me is that Literal controls do not implement the "CssClass" property. So, if you want to display a tag with server-side functionality that gives you the ability to apply a CSS class, then go ahead and use that Label.

No comments:

Post a Comment