Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am writing an APS.NET MVC application that reads data from DB and presents it with google charts.

I am reading the data from DB in C# into 2D array and need to pass it to my javascript code that generates the google chart.

My Code:

ViewBag.Data = new object[,]
        {
            {"10:00:00",10},
            {"11:00:00", 20}
        };

@{
    Object[,] arr = ViewBag.Data;    

}

My Javascript code:

var jsArray = @Html.Raw(Json.Encode(arr));// Only working for 1D array
var data = google.visualization.arrayToDataTable(jsArray);

I can't pass 2D array from my C# code to my javascript code to generate the wanted chart. I see only example for converting 1D arrays from C# to javascript (see above).

Any ideas?

Thanks

share|improve this question

You could try the JavascriptSerializer C# class (http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx). It basically converts a C# object to JSON.

share|improve this answer
    
I am using 2D array and sending my javascript code a serialized 2D array (string jsonArr = JSONHelper.ToJSON(objArr);), however the JSON string I get is for a 1D array, then the Json.Parse(@jsonArr) fails. Any ideas? – user917588 Apr 8 '13 at 8:25
    
Found an answer for that in: [stackoverflow.com/questions/8139265/… serialize 2D array). However the JSON parsing line var jsonParsedArray = Json.parse(@jsonArr); still fails (page is not loaded correctly). – user917588 Apr 8 '13 at 8:35
    
Have you tried the class i suggested? JavascriptSerializer. I believe it will do the work – nemo Apr 8 '13 at 8:43
    
Yes I did. It take the following array: object[][] objArr = new object[][] { new object[]{"NULL", "Series1"}, new object[]{"10:00:00",10}, new object[]{"11:00:00", 20} }; and converts it to: "[[\"NULL\",\"Series1\"],[\"10:00:00\",10],[\"11:00:00\",20]]", then I take this string and in javascript function writes var jsonParsedArray = JSON.parse('@jsonArr'); and that gives me an error. Do you see why it can't parse this string to a javascript 2D array? Thanks – user917588 Apr 8 '13 at 8:49
    
when I write JSON.parse("[[\"NULL\",\"Series1\"],[\"10:00:00\",10],[\"11:00:00\",20]]") it works as it should. You pass the wrong parameter to the JSON.parse function. '@jsonArr' is a string, try @jsonArr without the '' – nemo Apr 8 '13 at 9:03

Can't you serialize it to JSON in your C# code and parse it (JSON.parse) in your javascript code ?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.