views:

56

answers:

2

I am trying to call javascript from the page code behind on a button click using the following code.

System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("<script language=\"javascript\">");
                sb.Append("alert(\"Some Message\")");
                sb.Append("</script>");
                ClientScript.RegisterStartupScript(this.GetType(), "Alert", sb.ToString());

But the javascript is not getting called.

All I want to achieve from this is a popup msg on button click. I dont want to prevent server code execution.

+1  A: 

It seems you're using AJAX Update Panel. If so - you should use ScriptManager to execute your script:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("<script language=\"javascript\">");
                sb.Append("confirm(\"Some Message\")");
                sb.Append("</script>");
ScriptManager.RegisterStartupScript(
                             page, 
                             page.GetType(),  
                             "Alert", 
                             sb.ToString(), 
                             true);

However, it will not prevent your server-side code from execution if user answer "No" in your Confirm window.

Pavel Morshenyuk
I dont want to prevent the server code execution. All I want is just a popup on button click
Nadeem
In this case my code should work :)
Pavel Morshenyuk
I am not using AJAX update Panel. Is there any way to call this without that?
Nadeem
yep try ClientScript.RegisterClientScriptBlock();
Tigger
Even RegisterClientScriptBlock() is not working.
Nadeem
Nadeem, i've tried RegisterClientScriptBlock from a test page and it works fine. Could you give any more information or a full code sample?
Tigger
A: 

Hi Nadeem,

If your registering from a button event in an AJAX update panel, try;

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptName", sb.ToString(), true);

Cheers Tigger

Tigger