0

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.

2
  • Can you show what is the value of data? Commented Apr 30, 2022 at 9:05
  • Added data to the post, thanks. Commented Apr 30, 2022 at 9:13

1 Answer 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]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Looks fine. You can use Array.isArray() to check for data[name] as alternative of checking by the field name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.