Click here to Skip to main content
13,353,322 members (52,113 online)
Rate this:
Please Sign up or sign in to vote.
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:
    var array = @Html.Raw(Json.Encode(@ViewBag.Data));
       var jScriptArray = new Array();
        for (var i = 0; i < array.length; i++) {

        jScriptArray[i] = array[i];



Any help would be appreciated,thanks
Posted 14-Feb-13 4:49am
Updated 14-Feb-13 5:12am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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'}]};
var newArray = [];
for(var i=0, j=array.Books.length; i<j; i++){
you use
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

Either previously you create dimension for array or use push method for allocate dynamically.
pln474 15-Feb-13 2:29am
Thank you S.M Ahasan Habib, I think I understood the problem. My json data is like this:


I am beginner for this subject. So I don't know how can I give a name to json data.If you can explain this,I would be so happy.Thanks.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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}];
var newArray = [];
for(var i=0, j=array.length; i<j; i++){
pln474 15-Feb-13 4:56am
Thanks again but my data is came from database, I mean it is dynamic and based on user input. So I need to assign this data to a variable. I actually use mvc pattern. In my model I connect database and operate a stored procedure. My controller returns Json data according to my view which takes user input (start time and end time). Thanks again
S. M. Ahasan Habib 15-Feb-13 5:42am
Instead of jScriptArray[i] = array[i]; you will use jScriptArray.push(array[i]); in your code and it will work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.180111.1 | Last Updated 15 Feb 2013
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100