C# 从ASPX文件填充动态实例化页面的控件?

C# 从ASPX文件填充动态实例化页面的控件?,c#,asp.net,dynamic,webforms,httphandler,C#,Asp.net,Dynamic,Webforms,Httphandler,目前我有一个Example.aspx文件(没有代码隐藏),我想加载它,填充它拥有的控件,获取它的输出,并对它做一些事情(在http处理程序中) 我现在做的是: // Gets the page and instantiates it? Type type = BuildManager.GetCompiledType("~/Example.aspx"); Page page = (Page)Activator.CreateInstance(type); // ProcessRequest of

目前我有一个Example.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);

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

使用activator创建页面实例时,您可以在处理http请求时连接init或load event以执行其他代码。别忘了它仍然是一个事件驱动的模型!我希望它能有所帮助。

在使用activator创建页面实例时,您可以在处理http请求时连接init或load event以执行其他代码。别忘了它仍然是一个事件驱动的模型!我希望这会有帮助。

为什么要这样做?(我问完全出于好奇)这只是一个实验,还是你有一个特定的目的?@jwiscarson:这既是一个实验,也是尝试使用asp.net进行简单的模板制作。我希望asp.net来实现我自己的模板系统,而不是实现我自己的模板系统。@TimSchmelter:这种方法似乎不允许我们用数据填充页面中的现有控件,但谢谢。您查看了吗?它们有时使用起来很笨拙,但听起来您的目标与它们的实现类似。为什么要这样做?(我问完全出于好奇)这只是一个实验,还是你有一个特定的目的?@jwiscarson:这既是一个实验,也是尝试使用asp.net进行简单的模板制作。我希望asp.net来实现我自己的模板系统,而不是实现我自己的模板系统。@TimSchmelter:这种方法似乎不允许我们用数据填充页面中的现有控件,但谢谢。您查看了吗?它们有时使用起来很笨拙,但听起来您的目标与它们的实现类似。