2011-04-29 87 views
0

我想在用户提交页面时显示Javascript。我通过后面的代码调用这个Javascript(我认为这很简单)。这里是我的代码:从CodeBehind页面显示Javascript不工作!

MessageBox1("Testing my Message"); //Calling Function! 

private void MessageBox1(string msg) //This is in the code behind of the page. 
    { 


     // Cleans the message to allow single quotation marks 
     string cleanMessage = msg.Replace("'", "\\'"); 
     string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>"; 

     // Gets the executing web page 
     Page page = HttpContext.Current.CurrentHandler as Page; 

     // Checks if the handler is a Page and that the script isn't allready on the Page 
     if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
     { 
      page.ClientScript.RegisterClientScriptBlock(typeof(CommSetup), "alert", script); 
     } 


    } 

这不工作......我在做什么错在这里?谢谢!

+1

发布呈现的JavaScript以及服务器端代码。 – Oded 2011-04-29 14:48:46

回答

1

使用此静态方法来弹出警报:

public static void JS_Alert(string message) 
    { 
     // Cleans the message to allow single quotation marks 
     string cleanMessage = message.Replace("'", "\\'"); 
     string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>"; 

     // Gets the executing web page 
     Page page = HttpContext.Current.CurrentHandler as Page; 

     // Checks if the handler is a Page and that the script isn't allready on the Page 
     if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
     { 
      page.ClientScript.RegisterClientScriptBlock(typeof(Utilities), "alert", script); 
     } 
    } 

编辑:“管理工具”应该是类的名字你把这个方法煤矿发生被称为实用程序。如果你把它放在代码隐藏部分类中,它通常称为你的网页在最后被称为.cs。

+0

实用程序未被识别.... – 2011-04-29 15:23:19

+0

有关更多信息,请参阅编辑。 – MAW74656 2011-04-29 15:39:09

+0

我这样做,看看我的编辑代码。它没有显示我的脚本...它正在功能中,但没有向我显示脚本... – 2011-04-29 17:13:01

2

而不是使用文字的,使用ClientScriptManager:

Page.ClientScriptManager.RegisterStarupScript("startup", 
     "<script language='javascript'>window.location=''; window.alert('" + msg.Replace("'", "\\'") + "') </script>", false); 

我忘了究竟需要多少参数,但它会是这个样子。如果使用ScriptManager,还有:

ScriptManager.RegisterStartupScript(this.GetType(), "startup", ..); 

也是。

HTH。