I have an array inside array every object has file object Eg [ { file:fileObject, Description:string }, { file:fileObject, Description: string } ] How can i pass this array in formdata and also the controller net core catch data from formdata
1 Answer
If you post data by ajax,you need firstly know the two things below:
1.For each property of the complex type, model binding looks through the sources for the name pattern prefix.property_name. If nothing is found, it looks for just property_name without the prefix.For model you receive in backend is a List,you need give the name like:[index].FormFile or model[index].FormFile.
2.Your model has a IFormFile and your action receives a list model,if you only pass the IFormFile you need remove FromForm attribute and be sure do not have [ApiController].It is a known github issue and this has been moved to Next sprint planning milestone.
Here is a whole working demo:
Model:
public class FileModels
{
public string Description { get; set; }
public IFormFile FormFile { get; set; }
}
View:
<input type="file" multiple onchange="saveDocuments(this.files)"/>
<div class="form-group">
<input type="button" value="Submit" id="submit" class="btn btn-primary" />
</div>
@section Scripts
{
<script>
function saveDocuments(documentList) {
if (documentList.length > 0) {
var form = new FormData();
for (var i = 0; i < documentList.length; i++) {
var file = documentList[i];
form.append('model['+i+'].FormFile', file);
}
savePhysicalFile(form);
}
}
function savePhysicalFile(formData) {
if (formData != null) {
$.ajax({
url: "/Home/Save",
type: 'POST',
dataType: "json",
contentType: "multipart/form-data",
data: formData,
processData: false,
contentType: false,
success: function (result) {
console.log("Success", result);
},
error: function (data) {
console.log(data);
}
});
}
}
</script>
}
Controller:
[HttpPost]
public void Save(List<FileModels> model)
{
//...
}
If you post data by form submit,here is a whole working demo:
@model FileModels
<form asp-action="Save" method="post" enctype="multipart/form-data">
@for (int i = 0; i < 3; i++)
{
<div>
<input type="text" asp-for="Description" name="[@i].Description" />
</div>
<div>
<input type="file" asp-for="FormFile" name="[@i].FormFile" />
</div>
}
<div class="form-group">
<input type="submit" value="Submit" id="submit" class="btn btn-primary" />
</div>
</form>
Controller:
[HttpPost]
public void Save(List<FileModels> model)
{
//...
}
Result2:

