Label Controls and Literal Controls
Both Label and Literal controls are used to control the text displayed on a page at runtime. The text to be displayed is set in the controls’ Text property, as shown in Example 4-4.
Example 4-4. Declaring labels and literals
<asp:Literal ID="Literal1"
runat="server" Text="This is a literal" />
<asp:Label ID="Label1"
runat="server" Text="This is a label" />So, why have two controls for plain text? The answer is one of context. Add a new page called LabelsAndLiterals.aspx to the C4_BasicControls website, and add the code from Example 4-4 to it. Press Ctrl-F5 to run the page (or right-click the page and select View in Browser) and then have a look at the HTML generated by the two controls by right-clicking the page in the browser and selecting View Source. The key is that the Label control has wrapped its text in <span> tags whereas the Literal control has not:
This is a literal
<span id="Label1">This is a label</span>The <span> elements enable you to control the formatting of the text in a Label control, which is why the Label control has many display-related properties whereas the Literal control has none. For example, you can add text formatting to Label controls inline or through a Cascading Style Sheet (CSS) like so:
<asp:Label ID="Label2" runat="server" ForeColor="Blue"
Font-Bold="True" Text="This is a label styled inline" />
<asp:Label ID="Label3" runat="server" CssClass="StandardText"
Text="This is a label styled with CSS" />The resultant HTML ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access