Home > Back-end >  Passing multiple files as array or list from AJAX to Controller
Passing multiple files as array or list from AJAX to Controller

Time:12-27

I am trying to upload multiple files and then passing it to my Action in controller. The code is working fine but I am sure it can be made better because right now I am doing it sort of manually.

I am getting number of records from database against which I want to show file upload element. Number of records is not fixed, and it could be anywhere from 1 to 10 or may be more.

HTML Code

@{
    foreach(FileModel fileModel in Model.FileModel)
    {
        <input type="file" id="@("originalFile"   i)" />
    }
}

AJAX Code

for(i = 1; i <= @Model.FileModel.Count; i  )
{
    if($("#originalFile"   i).val() == "")
    {
        alert("You must upload all files");
        return false;
    }
    else
        model.append("originalFile"   i, $("#originalFile"   i)[0].files[0]);
}

C# Code [HttpPost]

public ActionResult UploadFiles(string masterRecordID, HttpPostedFileBase originalFile1 = null, HttpPostedFileBase originalFile2 = null, HttpPostedFileBase originalFile3 = null, HttpPostedFileBase originalFile4 = null, HttpPostedFileBase originalFile5 = null)
{

}

As you can see above is poor code as I am manually passing all files one by one. And number of files could be anything so how can make it dynamic i.e. somehow passing array or object of files from AJAX and then reading them all in controller?

CodePudding user response:

Actually, @QingGuo's answer (which he previously deleted) is correct in the concept.

Your UploadFiles API action needs to modify for originalFiles parameter as array/list to support multiple files.

public ActionResult UploadFiles(string masterRecordID, HttpPostedFileBase[] originalFiles)

And in your JS part:

model.append("originalFiles", $("#originalFile"   i)[0].files[0]);

  • Related