Passing arguments to JavaScript function from code-behind

104,334

Solution 1

You can use the Page.ClientScript.RegisterStartupScript method.

Solution 2

Look at the ScriptManager.RegisterStartupScript method if you're using a ScriptManager or any Ajax controls/asynchronous postbacks.

Edit:

Actually, the function you want is probably ScriptManager.RegisterClientScriptBlock

Solution 3

Some other things I found out:

You can't directly pass in an array like:

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",   
"<script>test("+x+","+y+");</script>");

because that calls the ToString() methods of x and y, which returns "System.Int32[]", and obviously Javascript can't use that. I had to pass in the arrays as strings, like "[1,2,3,4,5]", so I wrote a helper method to do the conversion.

Also, there is a difference between this.Page.ClientScript.RegisterStartupScript() and this.Page.ClientScript.RegisterClientScriptBlock() - the former places the script at the bottom of the page, which I need in order to be able to access the controls (like with document.getElementByID). RegisterClientScriptBlock() is executed before the tags are rendered, so I actually get a Javascript error if I use that method.

http://www.wrox.com/WileyCDA/Section/Manipulating-ASP-NET-Pages-and-Server-Controls-with-JavaScript.id-310803.html covers the difference between the two pretty well.

Here's the complete example I came up with:

// code behind
protected void Button1_Click(object sender, EventArgs e)
{
    int[] x = new int[] { 1, 2, 3, 4, 5 };
    int[] y = new int[] { 1, 2, 3, 4, 5 };

    string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
    string yStr = getArrayString(y);

    string script = String.Format("test({0},{1})", xStr, yStr);
    this.Page.ClientScript.RegisterStartupScript(this.GetType(),
    "testFunction", script, true);
    //this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
    //"testFunction", script, true); // different result
}
private string getArrayString(int[] array)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.Length; i++)
    {
        sb.Append(array[i] + ",");
    }
    string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
    return arrayStr;
}

//aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function test(x, y)
    {
        var text1 = document.getElementById("text1")
        for(var i = 0; i<x.length; i++)
        {
            text1.innerText += x[i]; // prints 12345
        }
        text1.innerText += "\ny: " + y; // prints y: 1,2,3,4,5

    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button"
         onclick="Button1_Click" />
    </div>
    <div id ="text1"> 
    </div>
    </form>
</body>
</html>

Solution 4

include script manager

code behind function

ScriptManager.RegisterStartupScript(this, this.GetType(), "HideConfirmBox", "javascript:HideAAConfirmBox(); ", true);

Solution 5

Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");

breaking up the script keyword because VStudio / asp.net compiler doesn't like it

Share:
104,334
David Hodgson
Author by

David Hodgson

Updated on July 09, 2022

Comments

  • David Hodgson
    David Hodgson almost 2 years

    I would like to call a javascript function from an aspx control. For instance, suppose I had:

    <html xmlns="http://www.w3.org/1999/xhtml">
        <head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        function test(x, y)
        {
    
        }
    </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Button"
             onclick="Button1_Click"/>
        </div>
        </form>
    </body>
    </html>
    

    and in the code behind:

    protected void Button1_Click(object sender, EventArgs e)
    {
        // do stuff (really going to a database to fill x and y)
        int[] x = new int[] { 1, 2, 3, 4, 5 };
        int[] y = new int[] { 1, 2, 3, 4, 5 };
    
        // call javascript function as test(x,y);
    }
    

    Is there a way to do it?

  • David Hodgson
    David Hodgson about 15 years
    I am looking for client side execution after post back, sorry for not being more clear. So with this methodology, this would call an existing script on the page, correct?
  • Thomas Stock
    Thomas Stock about 15 years
    yes a javascript function called "test" will be executed immediatly after postback. This is useful for showing alert popups to the user. from googling: "ClientScript.RegisterClientScriptBlock is used to make sure a specific script is included in the header part of the page. The type and key parameters helps ensure that a given script is included only once even if RegisterClientScriptBlock is called multiple time for the same script (provided the same type and key)."
  • Thomas Stock
    Thomas Stock about 15 years
    I seem to have posted the wrong method before. You need "RegisterClientScriptBlock". (I edited it in my post)
  • pyrocumulus
    pyrocumulus about 15 years
    If you want to pass objects/arrays to your clientside javascript, you could look into ASP.NET & JSON (using a hiddenfield in your HTML). A good tutorial on ASP.NET & JSON is here: blogs.msdn.com/rakkimk/archive/2009/01/30/…
  • David Hodgson
    David Hodgson about 15 years
    Thanks, I'll take a look at it.
  • PedroC88
    PedroC88 over 12 years
    How does it work? I need to call a JavaScript function from codebehind without any parameters, but I don't see how to use this :S