views:

244

answers:

1

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.

A: 

Have you considered creating a new control base class for your application that inherits from the UserControl object, then the your custom user controls would be based off of that class instead of the user control. You could then create methods for injecting data into the controls in the base class that would be accessible from your controls.

public class DataDrivenUserControl : UserControl
{
// implement stuff here
}

Your controls could then inherit from this class

DataDrivenUserControl ctl = (UDataDrivenUserControl)page.LoadControl(controlSpec);
page.Controls.Add(ctl);
ctl.InjectData(data);// or however you want to implement data injection methods

Normally I woldn't recommended more inheritence depth for one function but it might work here.

James Conigliaro
What you suggest is a workable solution, but it seems inelegant to me. Plus, it requires specializing the UserControl, which I am trying to avoid.
Jeff Leonard