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=\"http://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 = "http://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 = "http://blogs.msdn.com/aribeiro";
    a.InnerText = "Antonio Ribeiro's Web Log";
   
    a.RenderControl(writer);    
  }


 


Comments (2)
  1. Charles Chen says:

    In any type of no-trivial control, this leads to rather pricey performance overheads, especially when you start to nest controls within a hierarchy.

    Using raw HTML directly is always preferred if performance is your number one concern.

  2. Right. This is a good choice for easier maintainance and readability. And when using ASP.NET Page Output Caching should always be considered.

Comments are closed.

Skip to main content