vbbox.plan

It is by will alone I write this stuff.

 

.NET: Implementing ToString() in self-rendering ASP controls

If you've ever created an ASP server control that inherits directly from System.Web.UI.Control instead of UserControl maybe you've found yourself trying to "stream" the markup out of the control without necessarily having to wait until it's being rendered on its container. If you haven't been in this obscure situation, please stop reading now.

Right. So, we have this control that handles its own rendering to do some verily foofy markup stuff. Normally you simply override Render and work with the HtmlTextWriter class passed to the method:

protected override void Render(HtmlTextWriter writer) {

    writer.WriteBeginTag("div");
    writer.WriteAttribute("class", "myPurpleDiv");
    writer.Write(HtmlTextWriter.TagRightChar);
    
    base.Render(writer);
    
    writer.WriteEndTag("div");
}

In this case we're simply wrapping the control's outer tag in another div that has some predefined CSS selector in our linked stylesheet. But what if you want to do this outside of the normal page rendering process for some reason? Simple, you build your own HtmlTextWriter:

public override string ToString() {
    System.Text.StringBuilder sb = new System.Text.StringBuilder(1024);
    System.IO.StringWriter innerWriter = new System.IO.StringWriter(sb);
    HtmlTextWriter writer = new HtmlTextWriter(innerWriter);

    this.Render(writer);

    writer.Flush();
    writer.Close();

    return sb.ToString();
}

As you can see, we're simply using a different InnerWriter to trick the HtmlTextWriter to work as it normally does when it's being called by a page. In this case, we just use a StringWriter, which will happily use a StringBuilder as a backing store. Of course you could even use a MemoryStream or any other valid stream writer type. Once we're done calling the entire render tree (of course this will output child controls and so on) we extract the string from the stringBuilder and return it.

Now this proves that you can have your markup and eat it!

<foofyMode status="off" />

 

 

 

 

 

 

 

 

© 2003-2004 Klaus H. Probst BLOGGER