ASP.NET Dynamic HTML with HTML Controls

There are many times that you need to process a data list and generate HTML to output to an ASP.NET page. Most of the time, a Repeater is the best choice for this, but sometimes using a Repeater is not practical because the HTML has too many levels or is built with too many conditionals. In these cases, you could use a StringBuilder and output the result to a Literal control, but working with strings can be error prone. My preferred method to add a Placeholder control to the page and then just add Controls to its Controls collection in the code behind.

This works out well if you want to use web controls, but not if you want to use HTML controls. One of the goals with web controls was to make the properties more consistent across controls, but if you are familiar with HTML, then using the HTML controls might be more natural because the properties match the attributes you are already familiar with.

The issue with HTML Controls is that they are not as friendly to work with. For many elements, such as divs, you will have to use the HtmlGenericControl class. Although web controls have a property for CssClass, this is not available for HTML controls. If you want to add a new div control with a CSS class, you will end up with something like this:

var divContainer = new HtmlGenericControl(“div”);
divContainer.Attributes.Add(“class”, “div-class”);

To improve on this syntax, I added a derived control with a CSSClass property:

public class HtmlClassedControl : HtmlGenericControl
{
public HtmlClassedControl(string tag) : base(tag)
{
}

public string CssClass
{
get { return GetAttribute(“class”); }
set { Attributes.Add(“class”, value); }
}
}

Next, I added another derived class for the div control to eliminate the constructor parameter:

public class HtmlDiv : HtmlClassedControl
{
public HtmlDiv() : base(“div”)
{
}
}

With these changes, the syntax becomes:

var divContainer = new HtmlDiv {CssClass = “div-class”};

That may not seem like much of a change, but if you are adding 20 or 30 controls with nesting and looping, it makes a huge difference in readability and maintainabiliy… not to mention less code to write. You could easily add classes for other HTML elements such as ordering list, list item, etc.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s