开发者

Pass a javascript array to a c# method

开发者 https://www.devze.com 2023-02-08 21:36 出处:网络
开发者_JS百科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 b
开发者_JS百科

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?


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号