2011-04-29 41 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。