Wednesday, October 1, 2008

Why does the javascript registered by Page.ClientScript.RegisterStartupScript not execute?

On my portal, the javascript registered via Page.ClientScript.RegisterStartupScript does not execute, which I used [script]alert("something")[/script] to confirm.

Since I created my portal web app in VS2008 with AJAX enabled, I thought there is some incompatibility between Page.ClientScript.RegisterStartupScript and AJAX. After searching online, I found a lot of posts about how to use ScriptManager.RegisterStartupScript to replace Page.ClientScript.RegisterStartupScript to make the registered javascript run. But this solution did not resolve my problem - the javascript still did not work.

Then I found below code snippet which I think I can use to test whether my page is using AsyncPostBack or syncPostBack.

if (ScriptManager.GetCurrent(base.Page).IsInAsyncPostBack)
ScriptManager.RegisterStartupScript(this, this.GetType(), “Rating_Script_” + this.ClientID.ToString() , script.ToString(), false);
else
this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, script.ToString());

To my surprise, running this code snippet shows my page is using sync post back. So I suspect that my problem may have nothing to do with AJAX.

By looking the code, I found so called "AJAX enabled" web app actually just put [asp:ScriptManager ID="ScriptManager1" runat="server" /] in the master page and that's it. It does not mean you have used any AJAX functionality yet. So my pages are actually just "AJAX enabled" but having no any AJAX functionality (e.g. UpdatePanel).

I stepped back and thought the problem without AJAX. Eventually, I found the problem is with the javascript itself. After I corrected the javascript, the javascript began to execute.

Before correcting:
[javascript]function master_startup() {alert("something")}[/javascript]

After correcting:
[javascript]alert("something")[/javascript]

No comments: