4

我正在使用 C# 中的静态类,并尝试使用Control.RenderControl()来获取Control.

不幸的是,控件(和所有子控件)使用事件冒泡来填充某些值,例如,在实例化时,然后调用RenderControl()以下内容:

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

我返回一个空字符串,因为OnLoad()从未被解雇。

有没有办法可以调用“假”页面生命周期?也许使用一些虚拟Page控制?

4

1 回答 1

9

我能够通过使用Pageand的本地实例来完成此操作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();

编辑

如果您需要控件存在于<form />标签中,则只需将一个添加HtmlForm到页面,然后将您的控件添加到该表单,如下所示:

// 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();
于 2014-01-08T13:35:58.067 回答