ASP.NET asp Literal Use

This ASP.NET article shows the aspLiteral literal control. It uses C# code-behind.

Asp literal. Text or HTML content can be directly inserted in ASP.NET.

This does not require a tag in the HTML. We add dynamic content and minimize the number of DOM elements in the rendered page. The asp Literal control is useful.



Example. Here we use the <asp Literal> control. This is a good way to render content from HtmlTextWriter or to add a comment to a page. First I show an example of the asp Literal tag in the aspx markup. Then we use it in C# source code-behind.



ASPX markup that uses asp Literal

<li><asp:Literal runat="server" ID="FeaturedCount1"/>

<li><asp:Literal runat="server" ID="CategoryCount1" />
    <i><asp:Literal runat="server" ID="CategoryText1" /></i>
    articles similar to this one</li>


Example 2. We can use code-behind in ASP.NET to "render" the above markup to actual concise page HTML. The above code shows a UL (unordered list), and we want the first list item to say "50 articles". FeaturedCount1 is where we will insert the 50.


Code file for ASPX markup: C#

public partial class SiteHome : MasterPage
    protected void Page_Load(object sender, EventArgs e)
	// Set the bottom article count message.
	FeaturedCount1.Text = SiteStructure.Instance.MapCount.ToString();
	// FeaturedCountSpan1.Text = "50";

	string categoryName = "Category"; // Just for example.
	int countCat = SiteStructure.Instance.CountCategory();

	CategoryCount1.Text = countCat.ToString(); // "5"
	CategoryText1.Text = categoryName; // "Category"


Example 3. The C# code references FeaturedCount1, CategoryCount1, and CategoryText1, all of which are <asp Literal> tags. Next we see how ASP.NET renders the literal tags into the actual page. All the markup disappears.


Output HTML

<li>50 articles</li>
    articles similar to this one</li>

The asp Literal tags are entirely replaced. The asp Literal tags are completely replaced by their Text content they are assigned. This eliminates the need to create dummy spans that will only confuse browsers.

Note: This method is efficient for client browsers to render, and also smaller for your bandwidth. The next section examines this.


Comments. I puzzled over the best way to insert an HTML comment directly into the page in ASP.NET. One excellent way is to use an asp Literal and set its Text to the comment, including the comment start and end blocks.


Tip: This will create a nice and clear markup comment. Make an asp Literal with an ID of Comment1.

Comment example statement: C#

// Shows HTML comment in ASP.NET.
Comment1.Text = "<!-- HTML comment with literal. -->";


Summary. We used asp Literal for the common problem of inserting dynamic markup, comments, or other text into an HTML page. It is far more logical than Response.Write, and more object-oriented.


And: It will help you keep your code logical and easy-to-maintain. It reduces DOM elements and helps with client and server performance.