Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working in AngularJS and trying to send data to my backend.

I noticed that when the variable in my service has this structure test = [Object, Object] it gets passed into a List<String> in my ASP.NET backend, but i have trouble passing test = Array(2) into my backend.

I see the formats when i am debugging and set a breakpoint on the variable.

Is there a difference between the two? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

The first case:

var x = { foo: "bar", qux: 123 };
var y = { baz: "123", yeen: { arr: [1,2,3] };

var test = [ x, y ]; // [Object,Object]

For the second case, refer to MDN's documentation for Array():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

new Array(arrayLength)

If the only argument passed to the Array constructor is an integer between 0 and 2^32 - 1 (inclusive), this returns a new JavaScript array with its length property set to that number

So your second case code presumably is:

var test = Array(2);

...this actually evaluates to [undefined,undefined]), however .NET (thus ASP.NET) does not have a concept of "undefined" (compared to null), so this value is not serializable to JSON (as JSON does not allow undefined values) - so this explains why it's failing.

If an "empty" array element is meaningful in your application you should use explicit null values instead - ideally using an array-literal like so:

var ret = [ null, null ];

Or if the number of elements is variable:

var ret = Array( 123 ); // This creates a 123-sized array, where every element is undefined. This cannot be serialized to JSON
ret.fill( null );       // This explicitly sets every element to a null value. The array can now be serialized to JSON.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...