2

我有以下 JavaScript 代码:

var x = ['CFMG','JMFMG','CPMAF'];
var y = $.param({'test':x});
var data = "Operation=xxx&" + y;
$.post(
    "xxx.ashx",
    data,
    function() { ... }
);

铬合金console.log(data)

Operation=xxx&test%5B%5D=4CFMG&test%5B%5D=JMFMG&test%5B%5D=CPMAF 

我的 ASP.NET 代码收到了这个:

{Operation=xxx&test%5b%5d=4CFMG&test%5b%5d=JMFMG&test%5b%5d=CPMAF}
[System.Web.HttpValueCollection]: {Operation=xxx&test%5b%5d=4CFMG&test%5b%5d=JMFMG&test%5b%5d=CPMAF}
base {System.Collections.Specialized.NameObjectCollectionBase}: {Operation=xxx&test%5b%5d=4CFMG&test%5b%5d=JMFMG&test%5b%5d=CPMAF}
AllKeys: {Dimensions:[2]}

全键

{Dimensions:[2]}
[0]: "Operation"
[1]: "test[]"

在即时窗口中,如果我输入,?var["Test[]"]我会得到:

?var["Test[]"]
"4CFMG,JMFMG,CPMAF"

如何将Test[]值转换为数组?

谢谢!

4

2 回答 2

2

将您的 javascrpt 数组转换为 json 对象,然后将您的数据发布到服务器。我建议您使用JSON.NET。它是一个开源库,可将您的 c# 对象序列化和反序列化为 json,反之亦然...

例如:

string json = @"{
  ""Name"": ""Apple"",
  ""Expiry"": new Date(1230422400000),
  ""Price"": 3.99,
  ""Sizes"": [
    ""Small"",
    ""Medium"",
    ""Large""
  ]
}";

JObject o = JObject.Parse(json);

string name = (string)o["Name"];
// Apple

JArray sizes = (JArray)o["Sizes"];

string smallest = (string)sizes[0];
于 2012-06-28T21:33:25.853 回答
1

我更改了我的 JavaScript 代码,现在可以了。

我曾经JSON.stringify将 JavaScript 数组解析为字符串并将其发送到 ASP.NET。

新的 JavaScript 代码:

var x = ['CFMG','JMFMG','CPMAF'];
var y = JSON.stringify(x);
var data = "Operation=xxx&test=" + y;
$.post(
    "xxx.ashx",
    data,
    function() { ... }
);

铬合金console.log(data)

Operation=xxx&test=["4CFMG","JMFMG","CPMAF"]

我的 ASP.NET 代码现在收到这个:

{Operation=xxx&test=%5b%224CFMG%22%2c%22JMFMG%22%2c%22CPMAF%22%5d}
[System.Web.HttpValueCollection]: {Operation=xxx&test=%5b%224CFMG%22%2c%22JMFMG%22%2c%22CPMAF%22%5d}
base {System.Collections.Specialized.NameObjectCollectionBase}: {Operation=xxx&test=%5b%224CFMG%22%2c%22JMFMG%22%2c%22CPMAF%22%5d}
AllKeys: {Dimensions:[2]}

全键

{Dimensions:[2]}
[0]: "Operation"
[1]: "test"

在即时窗口中,如果我输入,?vari["test"]我会得到:

?vari["test"]
"[\"4CFMG\",\"JMFMG\",\"CPMAF\"]"

ASP.Net 代码转换为数组

string[] blah = json.Deserialize<string[]>(vari["test"]);

即时窗口:?blah

?blah
{Dimensions:[3]}
[0]: "4CFMG"
[1]: "JMFMG"
[2]: "CPMAF"

非常感谢你!

于 2012-06-29T19:41:43.213 回答