Victor Santos
Victor Santos

Reputation: 350

How to deserialize JavaScript array using ASP.NET

I have the following JavaScript code:

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

Chrome console.log(data)

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

My ASP.NET code is receiving this:

{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]}

AllKeys

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

In the Immediate Window, if I type ?var["Test[]"] I get this:

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

How can I convert Test[] value into an array?

Thank you!

Upvotes: 2

Views: 2410

Answers (2)

Victor Santos
Victor Santos

Reputation: 350

I changed my JavaScript code and now it's ok.

I used JSON.stringify to parse the JavaScript array to a string and send it to ASP.NET.

New JavaScript code:

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

Chrome console.log(data)

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

My ASP.NET code is now receiving this:

{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]}

AllKeys

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

In the Immediate Window, if I type ?vari["test"] I get this:

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

ASP.Net code to convert to array

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

Immediate Window: ?blah

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

Thank you very much!

Upvotes: 1

Sheikh Ali
Sheikh Ali

Reputation: 1544

Well convert your javascrpt array into json object and than post your data to server. I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and vice versa...

For Example:

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

Upvotes: 2

Related Questions