Friday, December 14, 2007

How To Inject Javascript during partial postback in ASP.Net

Injecting Javascript Codes using ClientScriptManager class i.e. RegisterClientScriptBlock  in asp.net codebehind will not work for partial postback [ASP.NET AJAX Calls].
To make it work we need to use ScriptManager class's ScriptManager.RegisterStartupScript, ScriptManager.RegisterClientScriptBlock methods

Example:

string msg = string.Format("alert('Test Javascript from partial postback');");
ScriptManager.RegisterStartupScript(TestButton, typeof(Button),"Test_my_script",msg, true);

TestButton => The control which triggered the partial postback [It may be other controls which are inside the updatepanel]
typeof(Button) => System.Type object for a type
Test_my_script => any unique string as key
msg => Javascript code to be injected
true /false => Adds javascript script tags i.e. <script></script>

3 comments:

Nandy said...
This comment has been removed by the author.
NaReN said...

Instead of typeof(Button), this.GetType() can be used.
So no need to bother that, which control will raise post back.

Shanmuga Sundaram said...

Good one Senthil. I needed exactly this functionality.

Thanks,
Shan