1

I need to pass a js multidimensional array (the dimensions are not known at compile time) to my code-behind in c#, I have done this in the next way:

var AdjustItems = ""; //My string variable to store the array separated with '|' and '-'
for (var i = 0; i < adjusts.length; i++) { //adjusts is my js array
    AdjustItems += adjusts[i].Motive + '|' + adjusts[i].Amount.toFixed(2).toString() + '-';
}
if (AdjustItems != "") {
    AdjustItems = AdjustItems.substring(0, AdjustItems.length - 1);
}
g('arrAdjust').value = AdjustItems; //arrAdjust is my hidden input.

Is there another way to do this where I can get the array, like an array and not like a string in c#?

Elwi
  • 687
  • 1
  • 5
  • 15

1 Answers1

2

Is there another way to do this where I can get the array, like an array and not like a string in c#?

The only way to communicate between the client and server is with strings. Therefore, you must use a library like JSON to pass complex variables between the client and server.

You can use javascript's built-in JSON library to turn your array into a string. This would change your example to the following:

g('arrAdjust').value = JSON.stringify(adjusts);

Then, use a C# JSON parsing library to convert it to an array on the server side. This stackoverflow question may help you with C# and parsing the JSON.

Community
  • 1
  • 1
Brant Olsen
  • 5,628
  • 5
  • 36
  • 53