Monday, August 11, 2008

Simple Wildcard replacement on the Rendered Html of Asp.Net Page

This is a simple solution for implementing wildcard replacements in your pages. You may use this, if you want to replace some tokens / merge codes in the generated html by your personalized values.

System.Web.UI.Control has a virtual method called 'Render' of the following signature -

protected internal virtual void Render(
HtmlTextWriter writer

Since, all your ASP.Net pages and server controls are subclasses of this Control class, you can override this method and manipulate the html that's rendered from this control. So, using this method, we will intercept the render method and apply a global replacement on the tokens present in the generated html. The C# code looks like the following one -

21 protected override void Render(HtmlTextWriter writer)

22 {

24 MemoryStream stream = new MemoryStream();

25 StreamWriter memWriter = new StreamWriter(stream);

26 HtmlTextWriter myWriter = new HtmlTextWriter(memWriter);


28 base.Render(myWriter);

29 myWriter.Flush();


31 stream.Position = 0;


33 string renderedHtml = new StreamReader(stream).ReadToEnd();


35 renderedHtml = renderedHtml.Replace("$Name$", "Sohan");


37 writer.Write(renderedHtml);

38 writer.Close();

39 myWriter.Close();

40 stream.Close();

41 }

So, the steps are -

1. Intercept the rendering - override the Render method.

2. Get the generated html - invoke the Render method on the base class supplying it a simple memory stream writer. Then read the html from the stream. You can also make use of other TextWriter implementations including StringWriter.

3. Apply your replacements - use simple string.Replace or Regex.Replace for more control.

4. Now, write the replaced content on the original writer.

Hope it helps!