简体   繁体   English

大量传递数组值以使用c#进行代码编写

[英]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 数据变量通常需要是一个对象数组,每个对象都有两个键: namevalue我通常有两种方式

Method 1: This method serializes the whole array into one string (similar to what you are trying) and sends it across. 方法1:该方法将整个数组序列化为一个字符串(类似于您尝试的字符串),并将其发送出去。 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). 这样做的一个很大的缺点是,如果数组太长,它将发送一个很长的字符串,该字符串可能会超过限制(然后需要从Web配置中增加限制)。 A big advantage of this however is you could directly serialize the object into ac# object. 但是,这样做的一大优点是您可以将对象直接序列化为ac#对象。

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. 方法是将行data: JSON.stringify({ arr: values })更改为data: [{name:"values", value:JSON.stringify(values)}] ,然后在c#中访问values字符串并反序列化它。 In c# you need to have a code something like this: 在C#中,您需要有类似以下的代码:

JavaScriptSerializer js = new JavaScriptSerializer(); JavaScriptSerializer js =新的JavaScriptSerializer(); MyObject object = js.Deserialize(Request.Params('values')); MyObject对象= js.Deserialize(Request.Params('values'));

You now have an object of type MyObject that you could use. 现在,您可以使用类型为MyObject的对象。 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. 请注意,为了能够使用它,您将需要c#对象和js对象具有完全相同的格式。 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')) 请注意,在这种情况下,MyObject将是某些东西的数组,因此需要将其替换为以下内容: 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. 方法2:此方法可以将数组中的每个js项作为一个单独的项发送出去。 In the js code, add var i = 0; 在js代码中,添加var i = 0; before the $.ajax({ line. Then replace data: JSON.stringify({ arr: values }) with data: values.map(v => ({name: i++, value: v})) . $ .ajax({行。然后将data: JSON.stringify({ arr: values })替换为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... 现在,在您的C#代码中,您可以将数组的每个元素都访问为Request.Params("0")Request.Params("1") ,依此类推...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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