简体   繁体   中英

Why Array.Length = 1 when empty array is passed to function via ajax?

I am having a bit of a difficulty grasping this one:

var data = {
    // ...
    files: $("#asgnNew-Popup .attachments-block").find(".file").length > 0 
        ? $("#asgnNew-Popup .attachments-block").find(".file").map(function() { 
            return $(this).attr("data-fileid"); 
        }).get() 
        : JSON.stringify([]),
        // ...
};

This is part of my data parameter which is passed along with POST type request into C# .Net controller.

public class Dto {
    // ...
    public int[] Files { get; set; }
    // ...
}

All it basically translates into is either an array of ints or an empty array:

files: [1,2,3]

or

files: []

There is a slight problem with empty array. If it is specified as [] I get no data item files included in the post request. So I had to wrap it in JSON.stringify() .

But the strangest thing happens when I do something like this on the server:

postdata.Files.Length

I get a value of 1 returned (expecting a zero). And when I check that value:

postData.Files[0]

I get a value of 0 when I am not expecting there to be any values at all.

Can anybody shed some light what is happening here ?

I believe it is because of data mapping at client and server end.
At client end: In http post request the data is serialized/encoded to string and posted to server. Now it's server responsibility to parse these data correctly. In case of empty array [], you are sending the string for files '[]' .
You may inspect the network payload/body in browser debugger.

At server end: It will be mapped to the receiving data type by your .NET server framework. In this case files:'[]' , it is probably getting mapped to Files:[0] .
This is because a particular JSONReader while consuming JSON stream (say [] ) may treat it as opening and closing of an array and hence end up initiatalizing the Files to contain one element (with default integer member value 0 in c#).
Please read below links to get an idea and dig up further based on which serialization/deserialization being used at your server end.
Data Contract Serializer
Serialize and Deserialize JSON Data
JsonReader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM