Does anyone know how to pass a C# ASP.NET array to a JavaScript array? Sample code will also be nice.
Sorry if I was vague earlier guys. The question is actually quite simple. Let’s say for simplicity that in my aspx.cs file I declare:
int [] numbers = new int[5];
Now I want to pass numbers to the client side and use the data in the array within JavaScript . How would I do this?
You can use ClientScript.RegisterStartUpScript to inject javascript into the page on Page_Load.
Here’s a link to MSDN reference:
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
Here’s the code in Page_Load:
Notes: Use StringBuilder to build the script string as it will probably be long.
And here’s the Javascript that checks for the injected array “testArray” before you can work with it:
There’s 2 problems here:
Some consider this intrusive for C# to inject Javascript
We’ll have to declare the array at a global context
If you can’t live with that, another way would be to have the C# code save the Array into View State, then have the JavaScript use PageMethods (or web services) to call back to the server to get that View State object as an array. But I think that may be overkill for something like this.