Bind multiple input files into IEnumerable

99 Views Asked by At

I am using ASP.NET MVC for a small website. I can't find a way to bind multiple file inputs into one IEnumerable.

I have the following inputs in my view:

<input type="file" name="medical-certificate-file" id="medical-certificate-file">
<input type="file" name="manager-degree-doc-file" id="manager-degree-doc-file">

My model is looking like this:

public class Document
{
      public DocumentType DocumentType { get; set; }
      public IFormFile File { get; set; }
}

public class InputModel
{
      public IEnumerable<Document> Documents { get; set; }
}

I tried mapping the file the way I successfully map other form data - changing the name property:

<input type="file" name="Documents.File" id="medical-certificate-file">

This solution works, but of course only for one file. The second, logically, cannot be mapped with the same name.

I also tried to use asp-for, like this:

<input asp-for="Documents.ElementAt(0).File" type="file" name="medical-certificate-file" id="medical-certificate-file">

This solution doesn't even work for a single file. I also tried different varieties of it.

I should note that it is important that the input forms are multiple and not one with multiple files selection option. There are several files, not just two as I indicate in the example.

Thanks in advance for your time!

1

There are 1 best solutions below

1
Qing Guo On

The complex object binding makes use of a sequential index. The index must start at 0, and it must be sequential, as its name suggests. There must be no gaps. The index is placed in square brackets and added to the form field's name attribute e.g name="Documents[0].file"

Try to use name="Documents[0].file" to bind file to the IEnumerable Documents :

<input type="file" name="Documents[0].file" id="medical-certificate-file">
<input type="file" name="Documents[1].file" id="manager-degree-doc-file">

the demo like:

<form asp-action="Index"  enctype="multipart/form-data">

    <input type="file" name="Documents[0].file" id="medical-certificate-file">
    <input type="file" name="Documents[1].file" id="manager-degree-doc-file">

    <input type="submit" value="Create" />
</form>

result:

enter image description here

Or :

@for (var i = 0; i < 5; i++)
{
    <input type="file" name="Documents[@i].file" id="medical-certificate-file">
}

result: enter image description here