Wednesday, June 4, 2008

JavaScript not firing with UpdatePanel

Yesterday when I am dealt with textbox inside an UpdatePanel, I noticed that the JavaScript is not fire when the TextChanged handler is triggered.

I had the code lines as below to fire my JavaScript function.

string strScript = "javascript:alert('Testing')";
ClientScript.RegisterStartupScript(typeof(Page),"clientScript", strScript);


After working around with the bug, finally I found the cause. The ClientScript.RegisterStartupScript is just cannot working within an UpdatePanel. To work around the problem there are related static methods in the class ScriptManager that should be used when the control is used inside an UpdatePanel, as the following:

string strScript = "javascript: alert('Testing')";
ScriptManager.RegisterStartupScript(this.gridPanel, this.GetType(), "strScript", strScript, true);


In short, when you are using UpdatePanel in your form, don’t use ClientScript.RegisterStartupScript. More information please refers to:
http://asp.net/AJAX/Documentation/Live/mref/O_T_System_Web_UI_ScriptManager_RegisterStartupScript.aspx http://asp.net/AJAX/Documentation/Live/mref/M_System_Web_UI_ScriptManager_RegisterStartupScript_5_d03cd23f.aspx

Hope this can help you anyway. Cheers.

5 comments: