This is a simple solution for implementing wildcard replacements in your asp.net pages. You may use this, if you want to replace some tokens / merge codes in the asp.net 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(
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)
24 MemoryStream stream = new MemoryStream();
25 StreamWriter memWriter = new StreamWriter(stream);
26 HtmlTextWriter myWriter = new HtmlTextWriter(memWriter);
31 stream.Position = 0;
33 string renderedHtml = new StreamReader(stream).ReadToEnd();
35 renderedHtml = renderedHtml.Replace(“$Name$”, “Sohan”);
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!