RegisterStartupScript in AJAX Pages

By Akbar

Today I was modifying an ASP.net user control (a rating control) which register a script at startup to initialize itself. As I was expecting, when I placed that control in the ASP.Net UpdatePanel (for AJAX) the initialization script didn’t run after the AJAX callback and thus the control didn’t worked.

While looking at the code, I found that it was using Page.ClientScript.RegisterStartupScript to run the initialization script. I already know that for the AJAX callback the function to register startup script is ScriptManager.RegisterStartupScript. But now the problem was that I wanted to keep the original functionality so that it keep running on the page even which don’t have the ASP.Net ScriptManager control. So I found a one way of checking if the request is AJAX request on the following link:
http://gotjeep.net/Blogs/CommentView,guid,4be2f278-12e4-40d5-b154-0e8ecaf18fac.aspx

So I change the existing RegisterStartupScript function with following conditional code:

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());

With this change done, the control now initialize properly on the page startup and after the AJAX callback. Job Done.

Tags: , , ,