简体   繁体   English

在Javascript中访问ArrayList-ASP.Net MVC2

[英]Accessing ArrayList in Javascript - ASP.Net MVC2

I have ArrayList in my Model and want to iterate through it in javascript. 我的模型中有ArrayList,并希望在javascript中对其进行迭代。 I am using following code but its giving me error : CS0103: The name 'i' does not exist in the current context 我正在使用以下代码,但给了我错误:CS0103:名称“ i”在当前上下文中不存在

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

How do I solve this? 我该如何解决?

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. c#代码在执行javascript代码之前在服务器端执行,因此在执行c#代码时变量i不存在。 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 ac# loop, or client side in a js loop. 但是您需要在ac#循环中迭代列表服务器端,或者在js循环中迭代客户端。 You can't mix them together. 您不能将它们混合在一起。

That code doesn't work. 该代码不起作用。 The foreach is evaluated at client and the <% ... %> instructions are evaluated at server. 在客户端评估foreach,在服务器评估<%...%>指令。 For that reason "i" doesn't exists, it only exists on the client's browser. 因此,“ i”不存在,它仅存在于客户端的浏览器中。

If you want to use JS to parse the list, you need to convert it to a javascript array. 如果要使用JS解析列表,则需要将其转换为javascript数组。 The final result you need to produce is this a collection of objects in { } notation (as in { name: "a", value: "b" } ) and wrapped with []. 您需要产生的最终结果是用{}表示法收集对象的集合(如{ name: "a", value: "b" } )并用[]包裹。

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; 或者,创建一个返回JsonResult并返回数组的操作结果; the MVC framework should auto convert for you; MVC框架应为您自动转换; you'd have to request that with JavaScript via AJAX. 您必须通过AJAX使用JavaScript进行请求。

HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM