Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection always null when using [FromForm] attribute

I'm trying to post FormData including both a File and a Collection.

This is my Model:

public class Content
{
    public string Name { get; set; }
    public string Link { get; set; }
}
public class Model
{
    public IEnumerable<Content> Contents { get; set; }
    public IFormFile File { get; set; }
}

This is my action:

[HttpPost]
public async Task InsertAsync([FromForm]Model dataPost)
{
    await _services.Create(dataPost);
}

My FormData in JavaScript is:

const formData = new FormData();
formData.append("File", myFile, "image.jpg")
formData.append("Contents", arrayOfContent)

And here is the header:

'Content-Type': `multipart/form-data`

The "File" is working fine, but the "Content" is always null.

Where am I going wrong? Thank you!

like image 536
mikenlanggio Avatar asked Sep 01 '19 10:09

mikenlanggio


2 Answers

For test I used the following arrayOfContent:

var arrayOfContent = [];
arrayOfContent.push({ name: 'test', link: 'test.com' });
arrayOfContent.push({ name: 'test2', link: 'test2.com' });

And I used a for loop to append the array to the form data:

for (var i = 0; i < arrayOfContent.length; i++) {
    formData.append("Contents[" + i + "].Name", arrayOfContent[i].name);
    formData.append("Contents[" + i + "].Link", arrayOfContent[i].link);
}

And I in Visual Studio I can see that it can bind it:

enter image description here

like image 188
hujtomi Avatar answered Sep 30 '22 09:09

hujtomi


You need to convert your array to JSON string in ajax submit code like this

const formData = new FormData();
formData.append("File", myFile, "image.jpg")
formData.append("Contents",  JSON.stringify(arrayOfContent))

Then deserialize in your controller

like image 31
Tony Ngo Avatar answered Sep 30 '22 08:09

Tony Ngo