开发者

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 th开发者_运维知识库e 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.


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

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

Cheers Tigger


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜