Victor Santos Victor Santos - 1 month ago 5
Javascript Question

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!

Answer

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

I used JSON.stringify to parse javascript array to 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 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"

On 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!

Comments