Passing List of objects by appending it in jquery formdata

4.7k Views Asked by At

i came across a scenario in MVC 4 where i need to send an image along with list of objects in ajax call. How can i append it in formData? here is my formdata and ajax call

    var formdata = new FormData();
    var imgFile = document.getElementById('ProfilePic');
    var imgfileList = imgFile.files;
    formdata.append(imgfileList[0].name, imgfileList[0]);

    // Below Code is not workin
    formdata.append('Rent', $scope.RentTypes);
    // $scope.RentType = [{ id:1,price:5},{id:2,price:6}]

        $.ajax({
            url: url
            data: formdata,
            processData: false,
            contentType: false,
            type: 'POST'
        });

In controller, my action which is get called from ajax call is like this

  public ActionResult Upload(List<Rent> Rent)
{
}

Rent.cs

public class Rent
{
 public int id;
 public int price;
 public Available;
}
1

There are 1 best solutions below

0
On BEST ANSWER

In order to post back to a collection, you would need to construct the data with indexers so it can be bound by the DefaultModelBinder

....
formdata.append('[0].id', 1);
formdata.append('[0].price', 5);
formdata.append('[1].id', 2);
formdata.append('[1].price', 6);

$.ajax({
  url: url
  data: formdata,
  processData: false,
  contentType: false,
  type: 'POST'
});