我想在用户提交页面时显示 JavaScript。我通过后面的代码调用这个 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);
}
}
这不起作用...我在这里做错了什么?谢谢!
最佳答案
不要使用文字,而是使用 ClientScriptManager:
Page.ClientScriptManager.RegisterStarupScript("startup",
"<script language='javascript'>window.location=''; window.alert('" + msg.Replace("'", "\\'") + "') </script>", false);
我忘记了到底需要多少个参数,但它看起来像这样。如果使用 ScriptManager,还有:
ScriptManager.RegisterStartupScript(this.GetType(), "startup", ..);
也是。
HTH。
关于c# - 从 CodeBehind 页面显示 Javascript 不起作用!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5833569/