Creating HTML markup using HTML Controls object model

Although ASP.NET provides a great object model for handling Web Controls and HTML Controls, I often see code that creates HTML markup directly, by manipulating strings. An example:

private string GetSomeHtml()
{
string html = "<A HREF=\"https://blogs.msdn.com/aribeiro\">" + Server.HtmlEncode("Antonio Ribeiro's Web Log") + "</A>";

return html;
}

Despite being performant, this isn't easy to read or to maintain.

You should allways take advantage of templated HTML and Web Controls in Visual Studio.NET. If you need programmatically manipulate and HTML element, drag an HTML Control into your Web Form, right click it and select Run As Server Control. Your HTML control is now a server side component that can be manipulated using ASP.NET code.

Still, if you need to create HTML markup strings in your code and you don't want to do it using templated controls, you can always use the HTML Object Model. Here's an example.

  private string GetSomeHtml()
{
HtmlAnchor a = new HtmlAnchor();
a.HRef = "https://blogs.msdn.com/aribeiro";
a.InnerText = "Antonio Ribeiro's Web Log";

HtmlTextWriter htw = new HtmlTextWriter(new StringWriter());
a.RenderControl(htw);

return htw.InnerWriter.ToString();
}

Another example, using the Render event:

  protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
    HtmlAnchor a = new HtmlAnchor();
a.HRef = "https://blogs.msdn.com/aribeiro";
a.InnerText = "Antonio Ribeiro's Web Log";

a.RenderControl(writer);
}