简体   繁体   中英

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.

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.

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

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

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

Cheers Tigger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM