RG-3
RG-3

Reputation: 6188

Showing Javascript from CodeBehind Page NOT Working!

I want to show a Javascript when user submit a page. I am calling this Javascript through code behind (I think this was easy). Here is my code:

 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);
        }


    }

This is not working...What I am doing wrong here? Thank you!

Upvotes: 0

Views: 1840

Answers (2)

MAW74656
MAW74656

Reputation: 3539

Use this static method to pop the alert:

  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);
        }
    }

EDIT: "Utilities" should be the name of the class you place this method in. Mine happens to be called Utilities. If your putting it in the code-behind partial class, its usually called whatever your web page is called with .cs on the end.

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

Instead of using a Literal, use the ClientScriptManager:

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

I forget exactly how many parameters are required, but it would look something like this. If using a ScriptManager, there also is:

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

too.

HTH.

Upvotes: 2

Related Questions