Friday, September 12, 2008

ASP.NET Substitute Custom Control In Output-cached Page

ASP.NET output cache is great. For dynamic content inside output-cached pages, ASP.NET 2.0 introduces Substitution concept, where the dynamic content is retrieved and substituted for the Substitution control at run time.

Usually Substitution content is just a string. But we can extend it to render a custom server control. For example there's a custom control named MyCustomControl that needs to be displayed dynamically in a output-cached page. First we need to declare a Substitution:
<asp:Substitution runat="server" ID="subControl" MethodName="GetControlString" />
Inside the GetControlString static method:
    public static string GetControlString(HttpContext context)
{
StringWriter output = new StringWriter();
Page pageHolder = new Page();
MyCustomControl control = MyCustomControl();
//control.SetParameters();
//pageHolder.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
pageHolder.Controls.Add(control);

context.Server.Execute(pageHolder, output, false);
context.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");

return output.ToString();
}

[2009/06 Updated] HttpContext.Response.ContentEncoding needs to be defined specifically if you encounter the wrong character encoding issue inside the custom control.