使用jQuery AJAX post将JS数组传递给VB.Net

时间:2021-12-24 12:15:48

I'm passing a client-side JS array to server-side VB.NET code using a jQuery AJAX post request. I have a way that works, but I'm wondering about best practices. I started like this:

我正在使用jQuery AJAX post请求将客户端JS数组传递给服务器端VB.NET代码。我有办法,但我想知道最佳做法。我开始是这样的:

JS:

var myArray=["Apple","Banana"];
$.ajax({url:"myhandler.ashx", 
        data:{"myArray":myArray.toString()}, type: "POST"});

VB:

Dim myArray as String() 
    = HttpContext.Request.Form("myArray").Split(New [Char]() {","c})

In the JS, myArray.toString() converts my array to a comma separated string "Apple,Banana", and then in the VB, Split converts it back to an array of strings.

在JS中,myArray.toString()将我的数组转换为逗号分隔的字符串“Apple,Banana”,然后在VB中,Split将其转换回字符串数组。

Then I found out that ajax will serialize arrays for you automatically. So I can leave the .toString() off:

然后我发现ajax会自动为你序列化数组。所以我可以关闭.toString():

$.ajax({url:"myhandler.ashx", data:{"myArray":myArray}, type: "POST"});

When I did that, on the VB side I found that HttpContext.Request.Form no longer has a key "myArray" It is now called "myArray[]", and lo and behold, it is a comma separated string: "Apple,Banana".

当我这样做时,在VB方面,我发现HttpContext.Request.Form不再有一个键“myArray”它现在被称为“myArray []”,并且看,它是一个逗号分隔的字符串:“Apple,香蕉”。

Here are my questions:

这是我的问题:

1) Is there a built in way to deserialize in VB.NET that converts the comma separated string back into an array of strings?

1)在VB.NET中是否有内置的反序列化方法,将逗号分隔的字符串转换回字符串数组?

2) Is the Ajax serialization of my array just calling toString(), and if a deserialize function exists is it just calling Split() like I am?

2)我的数组的Ajax序列化只是调用toString(),如果存在反序列化函数,它就像我一样调用Split()吗?

3) Are there any advantages of using the built in serialization/deserialization other than just being standard? I can think of a disadvantage. I don't like that it renames my key by adding the square brackets.

3)使用内置的序列化/反序列化除了标准之外还有什么优点吗?我可以想到一个缺点。我不喜欢它通过添加方括号重命名我的键。

1 个解决方案

#1


0  

Convert the array to JSON:

将数组转换为JSON:

$.ajax({url:"myhandler.ashx", data:{"myArray":JSON.stringify(myArray)}, type: "POST"});

Deserialize the JSON array in .NET using Json.NET

使用Json.NET在.NET中反序列化JSON数组

#1


0  

Convert the array to JSON:

将数组转换为JSON:

$.ajax({url:"myhandler.ashx", data:{"myArray":JSON.stringify(myArray)}, type: "POST"});

Deserialize the JSON array in .NET using Json.NET

使用Json.NET在.NET中反序列化JSON数组