简体   繁体   English

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

[英]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 . 我正在使用C#中的静态类,并且我正在尝试使用Control.RenderControl()来获取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: 不幸的是,控件(和所有子控件)使用事件冒泡来填充某些值,例如,在实例化时,然后在以下方法上调用RenderControl()

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. 我返回一个空字符串,因为从不触发OnLoad()

Is there a way I can invoke a 'fake' page lifecycle? 有没有办法可以调用'假的'页面生命周期? Perhaps use some dummy Page control? 也许使用一些虚拟Page控件?

I was able to accomplish this by using a local instance of Page and HttpServerUtility.Execute : 我能够通过使用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();

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: 如果你需要控件存在于<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