将ViewBag数据转换为jscript数组 [英] converting ViewBag data to jscript array

查看:76
本文介绍了将ViewBag数据转换为jscript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将包含控制器中Json列表的Viewbag数据转换为我视图中的javascript数组。我使用了这样的代码,但它给出了语法错误

I need to convert Viewbag data which contains a Json list in my controller to javascript array in my view. I used such a code but it gives syntax error in

    var array = @Html.Raw(Json.Encode(@ViewBag.Data));
part of the code
Here are the codes in my view:
<script>
    var array = @Html.Raw(Json.Encode(@ViewBag.Data));
       var jScriptArray = new Array();
        for (var i = 0; i < array.length; i++) {

        jScriptArray[i] = array[i];

        }

 </script>



任何帮助将不胜感激,谢谢


Any help would be appreciated,thanks

推荐答案

仔细查看下面的代码并与您的代码进行比较,并尝试了解您的错误

carefully see the code bellow and compare with your code and try to understand your mistake
var array ={Books:[{id:1,name:'a'},{id:2,name:'b'}]};
console.log(array.Books.length);
var newArray = [];
for(var i=0, j=array.Books.length; i<j; i++){
    newArray.push(array.Books[i]);
}
console.log(newArray.length);

你使用

array.lengh

我猜任何json对象都可能在我的代码中更喜欢书籍。接下来,您需要使用push方法将元素添加到新数组。您使用

there i guess any json object might be ther like Books in my code. Next you need to use push method to add element to a new array. You used

jScriptArray[i] 



以前您为数组创建维度或使用push方法动态分配。


Either previously you create dimension for array or use push method for allocate dynamically.


如果这是您的数据那么没问题。你错过了javascript数组推送方法。

请检查代码

If that is your data then no problem. You missed the javascript array push method.
Please check the code
var array =[{"AutoKey":1,"MachineGroup":"Atyc","StartDate":"\/Date(1322002860000)\/","EndDate":"\/Date(1322027095000)\/","Duration":24235},{"AutoKey":2,"MachineGroup":"Fongs","StartDate":"\/Date(1322003160000)\/","EndDate":"\/Date(1322012194000)\/","Duration":9034},{"AutoKey":3,"MachineGroup":"Then","StartDate":"\/Date(1322005320000)\/","EndDate":"\/Date(1322019001000)\/","Duration":13681}];
console.log(array.length);
var newArray = [];
for(var i=0, j=array.length; i<j; i++){
    newArray.push(array[i]);
}
console.log(newArray.length);


这篇关于将ViewBag数据转换为jscript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆