从ASPX文件中填充动态实例化页面的控件

本文关键字:控件 实例化 动态 ASPX 文件 填充 | 更新日期: 2023-09-27 18:17:48

目前我有一个的例子。aspx文件(后面没有代码),我想加载它,填充它的控件,得到它的输出和做一些事情(在http处理程序)。

我要做的是:

// Gets the page and instantiates it?
Type type = BuildManager.GetCompiledType("~/Example.aspx");
Page page = (Page)Activator.CreateInstance(type);
// ProcessRequest of page here?
// Error happens here, the page doesn't have any controls (but there is a label).
((Label)page.FindControl("Label")).Text = "Hello World";
using (StringWriter output = new StringWriter())
{
    // Execute the page and output the result into the string writer.
    HttpContext.Current.Server.Execute(page, output, false);
    // Do something with the output (or save it, email it, etc)
    // ...in this case we render it.
    context.Response.ContentType = "text/html";
    context.Response.Write(output.ToString());
}

但是它不起作用,因为页面实例没有任何控件(需要创建子控件?)。

如果我添加:

page.ProcessRequest(HttpContext.Current);

它可以工作,但我认为它运行整个页面生命周期,其中包括将页面呈现给响应,这是我不想要的。

从ASPX文件中填充动态实例化页面的控件

当使用activator创建页面实例时,您可以在处理http请求时连接init或load事件来执行额外的代码。别忘了它仍然是一个事件驱动的模型!