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?

1

3 Answers 3

2

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

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

Comments

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

Comments

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

Comments

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.