'Why are the arrays null when I'm sending form data using .NET API and React?

DTO looks like this:

public List<IFormFile> Images { get; set; }
public int[] Numbers { get; set; }

Method Signature:

public async Task<IActionResult> AddSection([FromForm]TheDto theDto)

Add the form data in React:

const handleSubmit = (data: any) => {
    const formData  = new FormData();

    for(const name in data) {
        formData.append(name, data[name]);
    }

    postService.addSection(formData);
}

It's then sent using axios.

Other values go through fine which are not in an array. I've inspected the data being added to FormData and the data is correct, I have 2 arrays, one holding File[], the other holding number[] and the names match that of the DTO so I'm now at a loss. Have I missed something?

I've used the same method on a single image and that's worked fine.

Edit: If I log data in the above function, data has this:

{images: Array(2), numbers: Array(3)}
images: (2) [File, File]
numbers: (3) [40, 43, 77]

Further edit: I can see that the issue is that when I'm appending the data, I'm only adding the string value for the arrays. So I think that the 2 issues are making sure I'm appending the data in the arrays properly and in a way that the .NET array understands to bind the data correctly.



Solution 1:[1]

There may be a better way of doing this and I'd be happy to listen to any better ways but I changed the way I appended the data for the arrays, it's now working ok.

for(const name in data) {
    if (Array.isArray(data[name]) {
        for (let i = 0; i < data[name].length; i++) {
            formData.append(name, data[name][i]);
        }
    } else {
        formData.append(name, data[name]);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1