开发者

Looping through values from c# array using javascript

Okay, I've created an array in c# and want to access the values in a javascript for loop. Here's my global c# variab开发者_C百科les:

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

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

And here's my ideal javascript code:

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

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?


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.

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.

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.

Something like this:

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


Hope it is useful to you... It was run fine in my test

    <script language ="javascript">
        var count = <%= count %>;
        alert(count);

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

    </script>


Sadly, I don't think so; because the Javascript is evaluated at run-time in the browser, but the server block is evaluated at compile time on the server.

You can probably just expand the scope of your server block and just loop through arr in C#


I am going to get flamed for this, but here goes:

Server-side:

protected void Page_Load(object sender, EventArgs e)
{
    string[] arr = new string[] { "1", "2", "3" };

    StringArr = string.Join(",", arr.Select(a => string.Format("\"{0}\"", a)).ToArray());
}

protected string StringArr;

Client-side:

<script language="javascript" type="text/javascript">
    var arr = [<%=StringArr %>];

    alert(arr.length);
</script>

Let the ridicule begin.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜