Tom
Tom

Reputation: 1057

Pass a javascript array to a c# method

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?

Upvotes: 5

Views: 1931

Answers (3)

Tj Kellie
Tj Kellie

Reputation: 6476

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); 

Upvotes: 2

Ray
Ray

Reputation: 21905

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"]

Upvotes: 0

khr055
khr055

Reputation: 29032

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

Upvotes: 2

Related Questions