Search code examples
asp.netvb.nethtmlcontrols

Creating HTMLControls versus outputting a string of HTML


I was recently trying to explain to a programmer why, in ASP.Net, they should create HTMLControls instead of creating HTML strings to create Web pages.

I know it is a better way of doing things, but I really couldn't give concrete reasons, other than, "This way is better."

If you had to answer this question, what would your answer be?

Why is

Dim divA as New HtmlControls.HtmlGenericControl("div") 
Dim ulList1 as New HtmlControls.HtmlGenericControl("ul") 
Dim liObj1, liObj2, liObj3 as New HtmlControls.HtmlGenericControl("li") 
liObj1.innerText = "List item 1" 
liObj2.innerText = "List item 2"
liObj3.innerText = "List item 3"
ulList1.Controls.Add(liObj1)
ulList1.Controls.Add(liObj2)
ulList1.Controls.add(liObj3)
divA.Controls.add(ulList1)

"better" than:

Dim strHTML as String
strHTML = "<div><ul><li>List item 1</li><li>List item 2</li><li>List item 3</li></ul></div>"

? It doesn't look better. Look at all that code! And, this is a very simplistic example, to save space. I don't think I would ever actually create a list manually like that, but would be iterating through a collection or using a more advanced Web control, but I'm trying to illustrate a point.


Solution

  • I don't do either. Instead, I:

    1. Create a custom control that encapsulates the desired construct
    2. or (very similar) create a simple class with the properties I want and override the .ToString() method to create the desired HTML.

    But of your two choices, a couple reasons the former is better are:

    • You can change properties of html controls or add other controls to the tree at later points in the page life cycle
    • ASP.Net is responsible for rendering the html. You're guaranteed not to have any mistakes that might break xhtml compliance.