繁体   English   中英

在ASP.NET中人工触发页面事件?

[英]Artificially firing Page Events in ASP.NET?

我正在使用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控件?

我能够通过使用PageHttpServerUtility.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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM