我正在使用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
控件?
答案 0 :(得分:9)
我能够通过使用Page
和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();