2

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 ?

7
  • possible duplicate of how to append whole set of model to formdata and obtain it in MVC Commented May 22, 2015 at 11:18
  • @StephenMuecke: That won't help me... Please read question, not title. Commented May 22, 2015 at 11:19
  • Because I send a custom list of object, this has nothing to do with form except choosing file from local computer. Commented May 22, 2015 at 11:21
  • Then just a matter or correctly naming what you post back (with indexers) so that it binds to your model. Commented May 22, 2015 at 11:23
  • IT works only if I add formData.append(data, "files[i]") and in action I put List<HttpPostedFileBase> data, works perfectly. I don't know why is not working with custom objects ... Commented May 22, 2015 at 11:33

1 Answer 1

2

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();
  ....
Sign up to request clarification or add additional context in comments.

2 Comments

How would you append if there are multiple lists List1, List2, how would you identify a particular list. How about formData.append('List1[' + i + '].File', files[i]);?
@BilalAhmed, If you model contains a collection property named List where each object in the collection contains a property named File, then that is exactly how you would do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.