Mohammad Nadeem
Mohammad Nadeem

Reputation: 9392

Javascript function from ASP.Net Code behind

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.

Upvotes: 0

Views: 1946

Answers (3)

scouty
scouty

Reputation: 3

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>");
}

Upvotes: 0

WooHoo
WooHoo

Reputation: 1922

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

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

Cheers Tigger

Upvotes: 0

Pavel Morshenyuk
Pavel Morshenyuk

Reputation: 11471

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.

Upvotes: 1

Related Questions