0

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

2 Answers2

0

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.

nemo
  • 1,675
  • 10
  • 16
  • 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 08 '13 at 08:25
  • Found an answer for that in: [http://stackoverflow.com/questions/8139265/json-net-incorrectly-serializes-a-two-dimensional-array-to-a-one-dimension](JSON serialize 2D array). However the JSON parsing line `var jsonParsedArray = Json.parse(@jsonArr);` still fails (page is not loaded correctly). – user917588 Apr 08 '13 at 08:35
  • Have you tried the class i suggested? JavascriptSerializer. I believe it will do the work – nemo Apr 08 '13 at 08: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 08 '13 at 08: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 08 '13 at 09:03
0

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

Alytrem
  • 2,620
  • 1
  • 12
  • 13