Accessing JavaScript arrays using the HTML DOM interop

10 April 2008

The documentation on the HTML DOM interoperability feature is definitely a little sparse today, but with the Beta 1 release of Silverlight 2, the APIs are very useful for getting a lot done.  Since we went for parity with JavaScript, it’s a super rich way to interact with existing AJAX controls and the web browser.

A very common request I hear is “how in the world do I access elements in a JavaScript array in managed code” ?

Since a JavaScript array is just a JavaScript object, and the array indices are just numbered properties, that means GetProperty is your answer.

Create a JavaScript array

Use the Eval method on the window to create a new array in JavaScript.  The ScriptObject reference allows you to interact with it:

C#
 

VB

Get a JavaScript array’s length

C#

VB
 

Return a single element

Individual elements are stored as numbered properties, just use GetProperty with the index of interest to retrieve an element:

C#

VB

A key developer in the Silverlight project for bringing this code is Wilco Bauwer, his first post on the HTML DOM interop is here

Hope this helps!

Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus