ASP.NET LiteralControl

ASPNET web programming framework

The ASP.NET LiteralControl renders text data. It is a way to embed a comment or text in the HTML source of each ASP.NET page rendered. Here we see an example of this web control and add a timestamp to our pages, using the C# language.

Example

Format

First, here is how to get the current time in the best format, which keeps the comments small, and also how to use LiteralControl to add a comment to your pages. We create a new LiteralControl and append it to the bottom of the .aspx page.

asp Literal Use
Code that uses LiteralControl: C#

static public string TimeString()
{
    return DateTime.Now.ToString("h:mm:ss");
}

protected void Page_Load(object sender, EventArgs e)
{
    LiteralControl literal = new LiteralControl("<!-- " +
	TimeString() + " -->");
    Page.Controls.Add(literal);
}
The current time: now

The DateTime.Now property is used to get the current time. On it, we call ToString with a formatting parameter string. The string indicates that we want the date with the "short" hour (1-12, not 0-23), and the minutes and seconds.

DateTime Format

Tip:This method is static.
It uses no instance members on the class.
More information on static methods is available.

Static MethodHypertext markup language: HTML

The Page_Load event runs each time the page is run. This is important for adding the LiteralControl at the bottom of each page. LiteralControl is simply a text string object that we can place quickly in the page.

Note:Look at how we use the constructor.
We specify that we want an HTML comment.
The TimeString() method is called.

And:This returns the "2:26:42" style time string.
We put it in the HTML comment.

Finally:In the above code, we append the LiteralControl to the document. This is an object-oriented way to add the comment.

Summary

We looked at the LiteralControl class. This is an object-oriented way of effectively adding timestamps to pages. You may also need to add timestamps to ASP.NET web controls, your HtmlTextWriter code, and other places.


C#: .NET: ASP.NET