views:

299

answers:

3

Hi

I have ArrayList in my Model and want to iterate through it in my javascript. I am using following code but its giving me error : CS0103: The name 'i' does not exist in the current context

    for(var i=0; i <= <%=Model.KeyList.Count%>; i++)
    {
        alert('<%=Model.KeyList[i]%>');      
    }  

How to get rid of this. its urgent...Please.

A: 

That code doesn't work. The foreach is evaluated at client and the <% ... %> instructions are evaluated at server. For that reason "i" doesn't exists, it only exists on the client's browser.

Elph
+1  A: 

This will not work. The c# code is executed at the server side before the javascript code is executed therefore the variable i doesn't exist when you execute the c# code. I can't really tell you how to fix it as you don't say what you want to do. But you ether need to iterate the list server side in a c# loop, or client side in a js loop. You can't mix them together.

Mattias Jakobsson
A: 

Hey,

If you want to use JS to parse the list, you need to convert it to a javascript array. The final result you need to produce is this a collection of objects in { } notation (as in { name: "a", value: "b" }) and wrapped with [].

So you need to generate this client code and parse it on the client, or scrap it and process it on the server. Or, create an action result that returns a JsonResult and return the array; the MVC framework should auto convert for you; you'd have to request that with JavaScript via AJAX.

HTH.

Brian