tags:

views:

233

answers:

5

I am developing a HTML form designer that needs to generate static HTML and show this to the user. I keep writing ugly code like this:

public string GetCheckboxHtml() { return ("<input type="checkbox" name="somename" />"); }

Isn't there a set of strongly typed classes that describe html elements and allow me to write code like this instead:

var checkbox = new HtmlCheckbox(attributes); return checkbox.Html();

I just can't think of the correct namespace to look for this or the correct search term to use in Google.

+1  A: 

One option is to use XElement functional construction. See this blog post for an example calendar generator.

In your case, your Html could be generated with:

var input = new XElement("input",
    new XAttribute("type", "checkbox"),
    new XAttribute("name", "somename"));

return input.ToString();
Jacob Carpenter
+2  A: 

You could use the classes in the System.Web.UI.HtmlControls namespace. Then you can use RenderControl to generate the html content.

HtmlInputCheckBox box = new HtmlInputCheckBox();

StringBuilder sb = new StringBuilder();
using(StringWriter sw = new StringWriter(sb))
using(HtmlTextWriter htw = new HtmlTextWriter(sw))
{
    box.RenderControl(htw);
}
string html = sb.ToString();
Cristian Libardo
This seems like a good solution, however I'm just concerned about the "heavy" nature of the HtmlControls included in ASP.NET. I have a great deal of distaste for ASP.NET WebForms (I prefer ASP.NET MVC) which might be prejudicing me. I really appreciate your input though.
Actually, I agree with you =)
Cristian Libardo
+5  A: 

Well, if you download the ASP.NET MVC DLL's (which you can use in any type of project... including Console apps)... then you can use the many HTML helpers they have.

Timothy Khouri
I like this solution a lot. I'm probably going to use this. I can't believe I forgot about the ASP.NET MVC HTML helpers. Thanks!
A: 

HtmlTextWriter contains goodies like "WriteStartTag" and "WriteEndTag", which can be used to create properly formed HTML fairly easily.

You essentially pass the tagname and attributes to the HtmlTextWriter, and it generates the proper HTML, and will close it properly with WriteEndTag.

You can also use the prewritten HTMLControls that wrap this code up into strongly typed classes.

FlySwat
A: 

Also consider using System.Xml. By using it, you almost guarantee your HTML is XHTML compliant.

tsilb