从代码隐藏页面显示Javascript工作!

时间:2011-04-29 14:46:16

标签: 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);
        }


    }

这不行......我在这里做错了什么?谢谢!

2 个答案:

答案 0 :(得分:2)

使用ClientScriptManager:

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

我确切地忘记了需要多少参数,但它看起来像这样。如果使用ScriptManager,还有:

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

HTH。

答案 1 :(得分: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调用。