Passing arguments to JavaScript function from code-behind

前端 未结 9 2042
孤街浪徒
孤街浪徒 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:32

     
        
    
    
    
    
    
    
    
        

    protected void Page_Load(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(" var y = test({0},{1}) ; ", xStr, yStr); script += String.Format(" document.getElementById(\"TextBox1\").value = y "); 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; }

提交回复
热议问题