开发者

Convert square bracket notation array from javascript to C# using JSON?

I have this:

var testArray = [];
testArray["First"] = "First Test开发者_C百科 Data";
testArray["Second"] = "Second Test Data";
$.toJSON(testArray);

I then pass it back to server side. When I look at the object server side in handling the AJAX request all I have is "[]".

Is there a way to do this or something similar to achieve the ability to look up data passed back from the client?


You have to make testArray an object:

var testArray = {};

The way you use arrays is not correct. Arrays only should have values with numerical indices. Otherwise you just add a property to the array object and these are ignored when converted to JSON.

DEMO


You are creating an array, but then you are using it as an object. Create an object instead, and it will be handled correctly:

var testObject = {};
testObject["First"] = "First Test Data";
testObject["Second"] = "Second Test Data";
$.toJSON(testObject);

or simply:

var testObject = {
  First: "First Test Data",
  Second: "Second Test Data"
};
$.toJSON(testObject);

If you really want an array, then you access the items using numbers, not strings:

var testArray = [];
testArray[0] = "First Test Data";
testArray[1] = "Second Test Data";
$.toJSON(testArray);

or simply:

var testArray = ["First Test Data", "Second Test Data"];
$.toJSON(testArray);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜