简体   繁体   中英

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).

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. Dont forget it is still an event driven model! I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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