Snake Eyes
Snake Eyes

Reputation: 16764

Send files through AJAX using FormData to ASP.NET MVC

I have a simple model:

public class MyModel {
   public string Description { get; set; }
   public HttpPostedFileBase File {get; set; }
}

and my MVC action:

[HttpPost]
public ActionResult Upload(List<MyModel> data) {
   // do soemthing
}

and finally JavaScript:

$("#chooseFile").on("change", function (){
    var files = $(this).prop("files");
    var array = [];    

   for(int i=0; i<files.length; i++) {
      var obj = {};
      obj.Description = "My custom description" + i;
      obj.File = files[i];

      array.push(obj);
   }

   var formData = new FormData();
   formData.append("data", array);

   var xmlHttpRequest = new XMLHttpRequest();
   xmlHttpRequest.open("POST", "/test/Upload");
   xmlHttpRequest.send(formData);
});

The problem is that data from the Upload action always has Count = 0 . Where is my mistake ?

Upvotes: 2

Views: 1126

Answers (1)

user3559349
user3559349

Reputation:

In order bind to a collection of complex objects, the names (in the name/value pairs) must include indexers. Your script needs to add the names to FormData in the following format - '[0].Files', '[0].Description', '[1].Files', '[1].Description' etc

$("#chooseFile").on("change", function() {
  var files = $(this).prop("files");
  var formData = new FormData();
  for(int i=0; i<files.length; i++) {
    formData.append('[' + i + '].File', files[i]);
    formData.append('[' + i + '].Description', 'My custom description' + i);
  }
  var xmlHttpRequest = new XMLHttpRequest();
  ....

Upvotes: 2

Related Questions