I figured it out. The following JavascriptInjector
class will work, although I don't know what the implications are of calling the render method in the PreRender
. Also think I may need to do something to figure out which type of HtmlTextWriter
that the base application is using.
"JavaScriptInjector.cs"
using System;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
public class JavascriptInjector : PlaceHolder
{
private bool performRegularlly;
public string InjectInto
{
get { return this.ViewState["InjectInto"] as string; }
set { this.ViewState["InjectInto"] = value; }
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreRender += this.__PreRender;
}
protected override void Render(HtmlTextWriter writer)
{
if (this.performRegularlly)
{
base.Render(writer);
}
}
private void __PreRender(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.InjectInto))
{
goto performRegularlly;
}
var injectInto = this.FindControlRecursively(this.Page);
if (injectInto == null)
{
goto performRegularlly;
}
performRegularlly = false;
using (var stringWriter = new StringWriter())
using (var writer = new HtmlTextWriter(stringWriter))
{
base.Render(writer);
writer.Flush();
injectInto.Controls.Add(new LiteralControl(stringWriter.GetStringBuilder().ToString()));
}
this.Controls.Clear();
return;
performRegularlly: this.performRegularlly = true;
}
private Control FindControlRecursively(Control current)
{
var found = current.FindControl(this.InjectInto);
if (found != null)
{
return found;
}
foreach (var child in current.Controls.Cast<Control>())
{
return this.FindControlRecursively(child);
}
return null;
}
}
Dave
2010-08-26 14:26:36