ASP.NET HTML control with clean output?

I am developing an ASP.NET web application at work and I am constantly facing the same problem:

Sometimes I want to write HTML to a page from code. For example, I have a page, Editor.aspx, with an output that changes depending on the value of the GET variable, "view". In other words, "Editor.aspx? View = apples" displays different HTML than "Editor.aspx? View = oranges."

I am currently outputting this HTML using StringBuilder. For example, if I wanted to create a list, I could use the following syntax:

myStringBuilder.AppendLine("<ul id=\"editor-menu\">"); myStringBuilder.AppendLine("<li>List Item 1</li>"); myStringBuilder.AppendLine("</ul>"); 

The problem is that I would rather use the ASP.NET List control for this purpose, because several lines of StringBuilder syntax prevent my code from being readable. However, ASP.NET controls tend to display convoluted HTML, with unique identifiers, inline styles, and a random block of inline JavaScript.

My question is: is there an ASP.NET control that just represents a common HTML tag? In other words, is there a control such as in the following example:

 HTMLTagControl list = new HTMLTagControl("ul"); list.ID = "editor-menu"; HTMLTagControl listItem = new HTMLTagControl("li"); listItem.Text = "List Item 1"; list.AppendChild(listItem); 

I know there are wrappers and such, but instead of taming the complexity of ASP.NET, I would rather start with get-go simplicity.

+4
source share
3 answers

is there an ASP.NET control that just represents a common HTML tag?

Yes, it is called HtmlGenericControl :)

As much as you don't need, but you can easily get around it:

 HtmlGenericControl list = new HtmlGenericControl("ul"); list.ID = "editor-menu"; HtmlGenericControl listItem = new HtmlGenericControl("li"); listItem.InnerText = "List Item 1"; list.Controls.Add(listItem); 

If you really need to switch to bare metal, you should use the HtmlTextWriter class instead of StringBuilder, as it is more customizable to pump raw HTML.

+8
source

If you just want to assign the results of your string editor to empty controls, you can use the <asp:Literal /> control for this.

+2
source

LiteralControl has a way with which you can pass your html ... I think it is better.

new LiteralControl (sb.ToString ());

+1
source

All Articles