问题描述:

I have this JS function :

var i = 0;

for (i = 0; i < myArray.length; i++) {

alert(myArray[i]);

}

but myArray[] is create on server side with c# :

ArrayList myArray = new ArrayList();

protected void Page_Load(object sender, EventArgs e)

{

foreach (MyObject myobject in MyObjects)

{

myArray.Add(myobject.Description);

}

}

so, how can I "pass" the C# array to Javascript? Or I need to print the whole javascript code on server side and send it to the server?

网友答案:

at before...

1)I will put a hidden in the page...

2) general a string like

"['a','b','c']" 

into the hidden at .cs

3) cast to the array from the string at javascript

var arr = eval(hiddenvalue);

4) use it as a array...

网友答案:

You can populate javascript array from serverside by using RegisterArrayDeclaration(arrayName, arrayValue) method.

In Cs file

RegisterArrayDeclaration("FavoriteNumbers", "1")
RegisterArrayDeclaration("FavoriteNumbers", "2")
RegisterArrayDeclaration("FavoriteNumbers", "3")

In javascript

<script language="javascript">
<!--
   var FavoriteNumbers =  new Array(1, 2, 3);
      // -->
</script>
网友答案:

You could create json object(array) that would be serialized and sent to client where you can work with it as with Javascript array.

You can use

using System.Web.Script.Serialization;


JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);

from

System.Web.Extensions.dll
网友答案:

You can serialize your C# array as JSON. You can read in detail about it here. Also I would suggest using List<> instead of ArrayList.

网友答案:

You can use PageMethods to access functions in your code behind. Simply create a function to access your property.

Example here, http://www.dotnetspider.com/resources/21456-Page-Method.aspx

相关阅读:
Top