Search code examples
c#asp.netrendercontrol

Artificially firing Page Events in ASP.NET?


I'm working with a static class in C#, and am trying to use Control.RenderControl() to get a string / mark-up representation of a Control.

Unfortunately the control (and all child controls) use event bubbling to populate certain values, for example, when instantiating, then calling RenderControl() on the following:

public class MyTest : Control
{
    protected override void OnLoad(EventArgs e)
    {
        this.Controls.Add(new LiteralControl("TEST"));
        base.OnLoad(e);
    }
}

I am returned an empty string, because OnLoad() is never fired.

Is there a way I can invoke a 'fake' page lifecycle? Perhaps use some dummy Page control?


Solution

  • I was able to accomplish this by using a local instance of Page and HttpServerUtility.Execute:

    // Declare a local instance of a Page and add your control to it
    var page = new Page();
    var control = new MyTest();
    page.Controls.Add(control);
    
    var sw = new StringWriter();            
    
    // Execute the page, which will run the lifecycle
    HttpContext.Current.Server.Execute(page, sw, false);           
    
    // Get the output of your control
    var output = sw.ToString();
    

    EDIT

    If you need the control to exist inside a <form /> tag, then simply add an HtmlForm to the page, and add your control to that form like so:

    // Declare a local instance of a Page and add your control to it
    var page = new Page();
    var control = new MyTest();
    
    // Add your control to an HTML form
    var form = new HtmlForm();
    form.Controls.Add(control);
    
    // Add the form to the page
    page.Controls.Add(form);                
    
    var sw = new StringWriter();            
    
    // Execute the page, which will in turn run the lifecycle
    HttpContext.Current.Server.Execute(page, sw, false);           
    
    // Get the output of the control and the form that wraps it
    var output = sw.ToString();