RegisterStartupScript and RegisterClientScriptBlock can work with UpdatePanel?!

Imagine you have a control which registers some trivial script, which has to be executed during loading of the page. To do that you will usually use following method:

page.ClientScript.RegisterStartupScript(…)


After some time, you decide to use the same control inside of UpdatePanel and find out that the script is not executed. To understand what the problem is please take a look on the following post. I investigated the problem with the release version of ATLAS and found out that the script is now even not rendered at all. The problem with UpdatePanel and registering of scripts is a little more trivial than expected.

The rendering of scripts by using of AJAX (ATLAS) works different way if UpdatePanel (or AJAX at all) is used. This is, because AJAX uses different rendering methods. For example, consider following code:

 

page.ClientScript.RegisterStartupScript(page.GetType(), Guid.NewGuid().ToString(), “alert(‘hello’)”, true);


This code ensures that word ‘hello’ is alerted when the request to page ends up. However, if this code is used inside of UpdatePanel, the message ‘hello’ will not be alerted. To work around the problem there are related static methods in the class ScriptManager which should be used, when the control is used inside of UpdatePanel.
Following example shows how to do that:

 

ScriptManager.RegisterStartupScript(page, page.GetType(), Guid.NewGuid().ToString(), “alert(‘hello’)”, true);


This solution seems to be very trivial. But, image what you have to do if the same control has to be used with and without of UpdatePanel even within the same application. Rick posted one possible solution here.

posted @ 2011-12-02 15:23  minglz  阅读(285)  评论(0编辑  收藏  举报