gpt4 book ai didi

c# - 在 ASP.NET 中人为触发页面事件?

转载 作者:太空狗 更新时间:2023-10-30 00:24:53 25 4
gpt4 key购买 nike

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

最佳答案

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

关于c# - 在 ASP.NET 中人为触发页面事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20996623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com