0

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.

2
  • 3
    are you really aware of the difference between client- and serverside? ... nothing more to say ... really ... Commented Oct 21, 2010 at 12:37
  • I tried the same code in Page_Load and it worked. Commented Oct 21, 2010 at 12:43

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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

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

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

Cheers Tigger

Comments

0

I encountered same problem once, all i wanted was to display a popup on Send Email button click. I achieved that doing following:

if(True)
{
 Response.Write(@"<script language='javascript'>alert('Your e-mail sent successfully!');</script>");
}
else
{
  Response.Write(@"<script language='javascript'>alert('Your e-mail sent Failed! Please Try Again');</script>");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.