How should an array be passed to a Javascript function from C#?

后端 未结 4 970
误落风尘
误落风尘 2021-02-02 17:59

I use a WebBrowser object from WPF and I\'m calling some Javascript code in the page loaded in the browser like this:

myWebBrowser.InvokeScript(\"myJsFunc\", new         


        
4条回答
  •  猫巷女王i
    2021-02-02 18:45

    You need to convert the array to a JS array first, something that looks like this:

    ["John", "Bob", "Sue"] // literal array
    

    Two examples follow:

    StringBuilder sb = new StringBuilder();
    string[] stringArray = bar.ToArray();
    
    //Build the JS array.
    sb.Append( "[");
    for (int i = 0; i < stringArray.Length; i++)
    {
        sb.AppendFormat( "'{0}', ", stringArray[i] );
    
    }
    sb.Append( "]");
    
    
    // Now send the array to the JS function.
    myWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, sb.ToString() });
    

    You may want to remove the trailing , as well. Don't forget to import the appropriate libraries for StringBuilder, which I think is System.Text.StringBuilder;

    or use, example two:

    string[] stringArray = bar.ToArray();
    
    // or simpler to use string join.
    string jsArray = "[" + String.Join( ",", stringArray ) + "]";
    //
    myWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, jsArray });
    

提交回复
热议问题