Saturday, March 24, 2012

AJAX and User controls which emit and execute Javascript

I have a user control which emits a bit of Javascript in its Render(HtmlTextWriter) method. When I use this control on a simple ASP.NET page with full page postbacks, it emits the Javascript which is then run by the browser.

However, when I naively drop this control into an UpdatePanel, when the panel gets updated the control renders the Javascript into the right place on the page, but the script is not run, so the control does not appear correct. Is it possible to achieve this somehow? (It ought to be, as we have an alternative AJAX package which does it without modification)

In order to achieve this you should not generate the script text in the Render method. Instead you should use ScriptManager.RegisterClientScriptBlock function. This will work for both postbacks as well as partial postbacks.

I've moved the script into a RegisterClientScriptBlock function, but it still appears not to be executed... here's my control's test OnPreRender() which does the registering, and I can see in the debugger it's called on both full and partial postbacks, but the Javascript alert() only fires off on full postbacks. Any ideas?

protectedoverridevoid OnPreRender(EventArgs e)

{

base.OnPreRender (e);if(Visible)

{

StringBuilder sb =newStringBuilder();StringWriter writer2 =newStringWriter(sb);

writer2.Write(

"<script type=\"text/javascript\">");

writer2.Write(

"//<![CDATA[");

writer2.Write(

"alert('hello world!');");writer2.Write("//]]>");

writer2.Write(

"</script>");

Page.ClientScript.RegisterClientScriptBlock(

this.GetType(),"__Map", sb.ToString());

}

}


Use ScriptManager.RegisterClientScript block not Page.ClientScript.registerClientScriptBlock
Sorry, my mistake. It works fine now... many thanks!

J.

No comments:

Post a Comment