views:

39

answers:

5

What is a LiteralControl? I was reading about LiteralContols but I am not sure why they are used. I used this code to list the controls in a page and - I have a page which has a label and a button. When I use this

foreach (Control control in Page.Controls)
{

Response.Write(control.GetType().ToString() + " - <b> " + control.ID + "</b><br />");    

      if (control is LiteralControl)
      {
           Response.Write("Textt :" + ((LiteralControl)control).Text.ToString() + " - " + Server.HtmlEncode(((LiteralControl)control).Text + "<br />") ); 
      }
}

I find that there are actually LiteralControls that are generated and listed before and after every control I have added to my page. Literal Controls also have only text property.

I am still not sure why LiteralControls are needed and used? Why are LiteralControls used? Why do controls that I add to my page have one LiteralControl placed before and after? And why do they have only Text Property?

+5  A: 

From MSDN Literal Control represents HTML elements, text, and any other strings in an ASP.NET page that do not require processing on the server.

Also have a look at this for Literal Control usage

A label renders a <span> tag. It allows you to programmatically change the display characteristics of some text you want to display. A LiteralControl renders exactly whatever static HTML you want it to. There is no general advantage of using one over the other. One may be more useful than another in certain circumstances. For example, if you want to display static text, and make no programmatic changes to it, you might want to use a LiteralControl.

Pandiya Chendur
+1  A: 

You will get a LiteralControl for any HTML markup that is not part of an ASP.NET server control. It's just how the framework renders the HTML shrubbery of your page. The Text property is just this HTML, which also includes any whitespace.

Chris Farmer
+2  A: 

A LiteralControl is used to inject HTML into your page at runtime.

Sky Sanders
+1  A: 

A lot of programmers who don't understand the value of semantic markup (especially those with primarily a Windows Forms background) will use a Label control or the HTML LABEL tag as a placeholder for programmatically-generated text on a page. The disadvantage to this is that Label has semantic meaning in an HTML document.

Using a literal gives you a control with an ID attribute to hook to, while allowing you to inject semantically correct markup around it.

Additionally, if you end up not pushing any text to a LABEL tag, it will still output the tag in your HTML, like so: <label></label>, whereas a Literal with no text will output nothing - much cleaner.

Superstringcheese
A: 

What I did in one web application was to hook into defined literal controls on the page to add text at runtime. A literal control creates no markup of its own, but will happily render any HTML that you provide to the Text property, just as well as raw text.

Grant Palin