5

I have an array that is created in javascript based upon checked items. Once this array gets created (integer array), how can I pass this to c#? Would it be easier to make a hidden text box and just add all the items in a string and just split that string up within c#? For example, if the checkboxes for rows 1,3,7 and clicked, my array is { 1,3,7 }. Again, would it be easier to have a hidden textbox that gets the string "1,3,7" and I just get the string from the text box?

Tom
  • 1,047
  • 3
  • 24
  • 44
  • There is a function to decode JSON in C#, isn't it? Array is a JSON too http://stackoverflow.com/questions/1334479/json-decoding-in-c – kirilloid Feb 07 '11 at 21:19

3 Answers3

2

I would pass the array to your C# code behind using an ajax post to a web method.

khr055
  • 28,690
  • 16
  • 36
  • 48
2

That is a perfectly acceptable way to pass a JS array to your codebehind file.

Just make sure you have an input control like a hidden field marked with the runat="server" and set the value of the control to the result of a .join(',') of your JS array. You can probably do this with the javascript function that created the array in the first place.

 var hiddenField = $get("<%= hdnFieldControl.ClientID %>");
 hiddenField.value = jsArray.join(',');

On the server you would then split the string value of the control again to reclaim your array.

var serverSideArray = hdnFieldControl.value.Split(new char[0]{',');

One note about this method, it will result in an array of strings. If you really want an array of int's you could convert it as another step:

int[] myInts = Array.ConvertAll(serverSideArray, int.Parse); 
Tj Kellie
  • 6,336
  • 2
  • 31
  • 40
0

If you give each checkbox a 'name' property with the same value, you will receive a comma-separated list:

<input type-"checkbox" name="whatever" value="1" />
<input type-"checkbox" name="whatever" value="3" />
<input type-"checkbox" name="whatever" value="7" />

Then in your code:

string values = Request.Form["whatever"]
Ray
  • 21,485
  • 5
  • 48
  • 64