What I would like to know is if there is a technique to inject parameters into the rendering HttpContext
such that it would be available to the UserControl
when its page life-cycle events (Page_Init, Page_Load) are called during rendering (during HttpContext.Current.Server.Execute()
)?
Such a technique would allow injecting data into any UserControl (say via a call to a remote service) without having to specialize it for dynamic rendering. It would load the same way as if it was a static control on an ASPX page.
Start with this base code fragment:
Page page = new Page();
UserControl ctl = (UserControl)page.LoadControl(controlSpec);
page.Controls.Add(ctl);
// want to inject data into the control at this point
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, true);
String renderedContent = writer.ToString();
return renderedContent;
I've seen the @ScottGu ViewManager example where he adds a Data member to each of his UserControls
and uses reflection to inject a data source into that member before the control is rendered into HTML.
I've also seen Stefan Sedich's take on the @ScottGu example where he derives a generic ViewManager<Control>
which allows the same thing but avoids the need for reflection.
For example, I would like to be able to add a parameter to the Request
object or to the QueryString
in the HttpContext before rendering the UserControl
.