简体   繁体   English

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

[英]Populate controls of dynamically instantiated Page from ASPX file?

Currently I have a single Example.aspx file ( with no code behind ) and I want to load it, populate the controls it has, get the ouput of it and do something with it (inside a http handler). 当前,我只有一个Example.aspx文件( 后面没有代码 ),我想加载它,填充它具有的控件,获取它的输出并使用它(在http处理程序内)进行某些操作。

What I am doing is this: 我在做什么是这样的:

// 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());
}

But it doesn't work since the page instance doesn't have any controls (needs to create child controls?). 但这不起作用,因为页面实例没有任何控件(需要创建子控件吗?)。

If I add: 如果我添加:

page.ProcessRequest(HttpContext.Current);

it works, but I think it runs the whole page life cycle and that includes rendering the page to the response, something I don't want. 它可以工作,但是我认为它可以运行整个页面生命周期,其中包括将页面呈现给响应,这是我不想要的。

When creating page instance with activator, you could hook up with init or load event to execute additional code while proccesing http request. 当使用激活器创建页面实例时,可以与init或load事件挂钩,以在处理http请求时执行其他代码。 Dont forget it is still an event driven model! 不要忘记它仍然是事件驱动的模型! I hope it helps. 希望对您有所帮助。

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

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