views:

485

answers:

3

I am developing an ASP.NET web application at work, and I keep running into the same issue:

Sometimes I want to write HTML to the page from the code-behind. For example, I have a page, Editor.aspx, with output which varies depending on the value of a GET variable, "view." In other words, "Editor.aspx?view=apples" outputs different HTML than "Editor.aspx?view=oranges".

I currently output this HTML with StringBuilder. For example, if I wanted to create a list, I might 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 ASP.NET's List control for this purpose, because several lines of StringBuilder syntax hamper my code's readability. However, ASP.NET controls tend to output convoluted HTML, with unique ID's, inline styles, and the occasional block of inline JavaScript.

My question is, is there an ASP.NET control which merely represents a generic HTML tag? In other words, is there a control like 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 the such, but instead of taming ASP.NET complexity, I would rather start with simplicity from the get-go.

+7  A: 

is there an ASP.NET control which merely represents a generic HTML tag?

Yes, it's called the HtmlGenericControl :)

As far as exactly what you want no, but you can get around it easily:

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 get down to bare metal then you should use the HtmlTextWriter class instead of a StringBuilder as it is more custom tailored to pumping out raw HTML.

Josh
Thanks for the HtmlTextWriter tip. What do you mean by "getting around it easily"?
attack
I have added a code sample to show what I mean. Essentially you just have to use the correct properties is all I was meaning. Also, if you really want absolute control over your output, then use the HtmlTextWriter as that is what all controls ultimately use under the hood in the Render() method. It does have a bit of a learning curve though.
Josh
+1  A: 

If you want to just assign the results of your stringbuilder to a blank control, you can use an <asp:Literal /> control for this.

Joel Coehoorn
+1  A: 

LiteralControl has constractor that you can pass your html... i think it is better.

new LiteralControl(sb.ToString());