使用JavaScript从C#通过数组循环值

问题描述:

好吧,我创建在C#中的数组,并希望访问循环一个javascript的值。这里是我的全局C#变量:

Okay, I've created an array in c# and want to access the values in a javascript for loop. Here's my global c# variables:

protected int count;
protected string[] arr = new string[20];

从那里我添加字符串值数组,让我们说,在Page_Load()事件。

From there I add string values to the array in, let's say, the Page_Load() event.

这是我的理想的javascript code:

And here's my ideal javascript code:

var count = <%= count %>;
for (var i = 0; i < count; i++) 
{
document.write(<%= arr[i] %>);
}

现在,如果我只使用ARR [0],将弹出一个带有ARR [0]正确的信息,所以我知道我得的那部分权利,但有使用该方式JavaScript变量我的&lt在里面;?%=%>标签

Now if I were to just use arr[0] that would pop up with the correct information for arr[0], so I know I've got that part right, but is there a way to use that javascript variable "i" inside the <%= %> tag?

在code的ASP.NET部分在服务器上执行。 JavaScript在浏览器中执行。服务器只看到JavaScript作为文字,它是没有意义的和非功能性。只有当浏览器收到的页面和跨$ P $点的JS是执行。

The ASP.NET parts of the code execute on the server. JavaScript is executed in the browser. The server just sees the JavaScript as text, it is meaningless and non-functional. Only when the browser receives the page and interprets the JS is it executed.

记住,服务器和客户端PC是通过网络连接的两个不同的系统。如果您要处理的系统B从系统中的数据,您需要将数据发送到B

Remember, the server and the client PC are two different systems connected by a network. If you want to process data from system A on system B, you need to send the data to B.

如果你想在阵列中的数据发送到浏览器,因此可以在一些JavaScript使用它,你需要serialize该数组。

If you want to send the data in the array to the browser so it can use it in some JavaScript, you need to serialize the array.

事情是这样的:

var myArray = <% = new JavaScriptSerializer().Serialize(serverSideArray) %>;
for(var i = 0; i < myArray.length; i++) {
    document.write(myArray[i]);
}