Passing arguments to JavaScript function from code-behind

前端 未结 9 2044
孤街浪徒
孤街浪徒 2020-12-03 17:54

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


    

        
9条回答
  •  盖世英雄少女心
    2020-12-03 18:33

    Some other things I found out:

    You can't directly pass in an array like:

    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",   
    "");
    

    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
    
    
        Untitled Page
        
    
    
        

提交回复
热议问题