0

We have a JavaScript Office add-in. We are making an installable and executable add-in on top of it by VSTO and WebView2.

I just realize that it's not obvious to pass an array value from C# to JavaScript. For instance, on the side of C#, I have the following code:

public object test()
{
    int[,] xx = { { 1, 2, 3 }, { 3, 4, 5 } };
    return xx;
}

In JavaScript, I have

test () {
    return new Promise(async (resolve, reject) => {
        try {
            let result = await window.chrome.webview.hostObjects.control.test();
            console.log(result)
            console.log(JSON.stringify(result))
            resolve(result)
        } catch (error) {
            reject(error)
        }
    })
}

Then, in the console of JavaScript, it shows Array(0) and []. If I pass a string value from C# to JavaScript, it works well.

Does anyone know how to pass an array from C# to JavaScript?

3
  • 1
    Write the script on the back end an post it. There's not enough info to provide an example. <% JavaScriptCode %>. Have you tried converting to JSON? Commented Jun 18, 2023 at 2:18
  • I believe this is one of the use cases dynamic was introduced for. But @AlexT. is right. More information is needed. I will note however that JavaScript does not support multi-dimensional arrays. It supports jagged arrays. Use a jagged array on the C# side as well if you're interoperating with the language that has no concept of a multi-dimensional array. Commented Jun 18, 2023 at 11:51
  • you can return Json object instead of returning object. the following link may help you. c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc Commented Jun 18, 2023 at 13:06

1 Answer 1

1

You must serialize objects and arrays to any format that suits your needs. But I think for JavaScript the most suitable format would be a JSON string, so you could get a ready made object in JavaScript. See Serialize c# array of strings to JSON array for more information.

Sign up to request clarification or add additional context in comments.

1 Comment

Finally, i use JsonConvert.SerializeObject on the side of C#, and JSON.parse on the side of JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.