max*_*axp 4 c# asp.net rendercontrol
我正在使用C#中的静态类,我正在尝试使用Control.RenderControl()
一个字符串/标记表示Control
.
不幸的是,控件(和所有子控件)使用事件冒泡来填充某些值,例如,在实例化时,然后调用RenderControl()
以下内容:
public class MyTest : Control
{
protected override void OnLoad(EventArgs e)
{
this.Controls.Add(new LiteralControl("TEST"));
base.OnLoad(e);
}
}
Run Code Online (Sandbox Code Playgroud)
我返回一个空字符串,因为OnLoad()
从未被解雇过.
有没有办法可以调用'假的'页面生命周期?也许使用一些虚拟Page
控制?
我能够通过使用本地实例来实现这一点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();
Run Code Online (Sandbox Code Playgroud)
编辑
如果您需要控件存在于<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();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
322 次 |
最近记录: |