c# - 从 CodeBehind 页面显示 Javascript 不起作用!

标签 c# javascript jquery .net asp.net

我想在用户提交页面时显示 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/

相关文章:

javascript - 当元素少于 3 时,旋转木马 slider 停止克隆

c# - 与客户端应用程序打包的最佳数据库

c# - 在 C# 中使用 HTTP API 的 Branch.io 链接

javascript - 在 ES6 类中使用 ES2016 Property Initializer Syntax 是一个好的 React 模式吗

javascript - 使用 Node 和 Firebase 循环访问数千条记录

javascript - TinyMCE动态HTML值问题

c# - 如何获取包含调用当前方法的方法的类的名称?

c# - 从 ASP.Net MVC 4 中的 Kendo UI MultiSelect 获取 PrimaryId

javascript - 练习 angularJS 窗口警报不起作用

javascript - ASP.NET MVC - 更改选项卡 AJAX RenderAction