Wednesday, June 24, 2009

Calling javascript from code behind

Previously, we know how to easily call server side method from javascript. The opposite is also simple enough.

Just use the RegisterClientScriptBlock method of ClientScriptManager (in case of full postback) or ScirptManager (in case of patial postback). Following is an example:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "confirmInPageNav", "<script>confirmInPageNav()</script>", false);

confirmInPageNav can be any javascript function


Xiaoguang said...

However, in the javascript function we'd like to run, we may not be able to get the reference to any control. It seems that the client document tree hasn't been built yet

Xiaoguang said...

If we are not able to get the reference to the controls in the javascript function, we can put the logic inside the pageLoad() method or document.ready() method. We then define a global bool value and run the logic only if the value is true. In the javascript function we'd like to invoke from code behind, simply set the bool value to true. Don't forget to set the bool value back to false at the end of the logic so that it won't run each time pageLoad() is executed.