Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


RegisterClientScriptInclude fails on partial postback in update panel
I had overridden OnPreRender in a custom control to register javascript libraries loaded from the Resources folder:

var scriptLocation = this.Page.ClientScript.GetWebResourceUrl(typeof(MyType), "MyScript.js");
this.Page.ClientScript.RegisterClientScriptInclude("js_id", scriptLocation);

However, if the control was in an updatepanel, and not visible until the postback, the script was not getting registered.

The solution was to NOT use the override OnPreRender. Instead manually fire your own event and handle it. I have no idea why this would be required - but it works.

Solution:

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// force an event to fire every prerender, even if control is in an AJAX update panel.
// the OnPreRender does seem to fire, but at the wrong order in the lifecycle and scripts don't get registered
// if the control was a) initially invisible, b) in an update panel, and c) set to visible on partial postback.
Page.PreRender += new EventHandler(CustomPage_PreRender);
}

void CustomPage_PreRender(object sender, EventArgs e)
{
base.OnPreRender(e);

var scriptLocation = this.Page.ClientScript.GetWebResourceUrl(typeof(MyType), "MyScript.js");
this.Page.ClientScript.RegisterClientScriptInclude("js_id", scriptLocation); Page.PreRender -= new EventHandler(CustomPage_PreRender); // done with this
}

Created By: amos 12/4/2013 12:56:31 PM