3

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?

1

5 Answers 5

5

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Y?? What ? don't know what you mean :)
4

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

Comments

3

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.

Comments

3

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

Comments

1

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...

Comments

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.