1

I need to pass a matrix from the C# code behind to javascript, however at the moment when my matrix is passed to the view, it is converted into a single dimensional array. In other words, my multi dimensional array is flattened by the serialization.

C# code

List<leituras> listaleituras = new List<leituras>();
public object[,] arrayTemperatura = new object[5, 3];
public JavaScriptSerializer javaSerial = new JavaScriptSerializer();

foreach (var leitura in listaleituras)
{
    arrayTemperatura[i, 0] = leitura.Data.Month.ToString() + "/" + leitura.Data.Year.ToString();
    arrayTemperatura[i, 1] = leitura.Sensor_temperatura;
    arrayTemperatura[i, 2] = leitura.Sensor_temperatura;
    i++;
}

Output

enter image description here

expected output format

[  
  ["09/18",95,95],["10/18",257,257],["11/18",1368,1368],["12/18",1574,1574],
  ["01/19",2437,2437],["02/19",3105,3105],["1/3",2096,2096],["2/3",1098,1098],
  ["4/3",361,361],["6/3",1993,1993],["7/3",2744,2744],["8/3",2891,2891],
  ["9/3",1797,1797],["11/3",3027,3027],["12/3",2996,2996],["13/3",2766,2766],
  ["14/3",3067,3067],["15/3",3043,3043],["16/3",2374,2374]
]

How do I pass a serialized multi dimensional array?

0

2 Answers 2

1

use JSON.NET

string json_string = JsonConvert.SerializeObject(arrayTemperatura);

it serializes multi-dimension arrays as you want.

then in javascript you can desrialize json using JSON.parse

var multidimentionArray = JSON.parse( json_string );

also see this

Sign up to request clarification or add additional context in comments.

1 Comment

in javascript I had to add: var array = JSON.parse('<%=jsonString%>'); console.log(array);
0

Use a jagged array instead of a two-dimensional array.

First of all declare your array without intialising it: public object[][] arrayTemperatura;

then do this after your while loop:

arrayTemperatura = new object[listaleituras.length][];

foreach (var leitura in listaleituras)
{
    arrayTemperatura[i] = new object[3];
    arrayTemperatura[i][0] = leitura.Data.Month.ToString() + "/"+ leitura.Data.Year.ToString();
    arrayTemperatura[i][1] = leitura.Sensor_temperatura;
    arrayTemperatura[i][2] = leitura.Sensor_temperatura;
    i++;
}

Alternatively you could use the Json.NET serializer instead of the JavaScriptSerializer - I have created an example to show that it just behaves the way you'd expect in your question: https://dotnetfiddle.net/2QBP7J

1 Comment

As a side note, assuming that leitura.Data is a DateTime, your formatted date could be done using arrayTemperatura[i][0] = leitura.Data.ToString("M/y");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.