简体   繁体   中英

passing array values in bulk to code behind using c#

我需要将值传递给从客户端到服务器端的代码后面,我该怎么做

The data send generally needs to be a key value pair. I don't think simply sending a string would work. The data variable generally needs to be an array of object, with each object having two keys: name and value I usually have two ways of doing this

Method 1: This method serializes the whole array into one string (similar to what you are trying) and sends it across. A big disadvantage of this is that if the array is too long it sends a really long string which may cross the limit (the limit then needs to be increased from web config). A big advantage of this however is you could directly serialize the object into ac# object.

The way is to change your line data: JSON.stringify({ arr: values }) into data: [{name:"values", value:JSON.stringify(values)}] and then access the values string in c# and deserialize it. In c# you need to have a code something like this:

JavaScriptSerializer js = new JavaScriptSerializer(); MyObject object = js.Deserialize(Request.Params('values'));

You now have an object of type MyObject that you could use. Note that in order to be able to use this, you will need the c# object and js object to be of the exact same format. Note that in this case the MyObject would be an array of something so it needs to be replaced with something like this: object = js.Deserialize<string[]>(Request.Params('values'))

Method 2: This method can take each js item in the array as a separate item and send it across. In the js code, add var i = 0; before the $.ajax({ line. Then replace data: JSON.stringify({ arr: values }) with data: values.map(v => ({name: i++, value: v})) .

Now in your c# code, you can acess each element of the array as Request.Params("0") , Request.Params("1") and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM