0

I have this javascript code:

  var formData = new FormData($('#formSlip').get(0));
  formData.append('myList', JSON.stringify(tests)); 

Where tests is a list of objects. I'm sending an ajax post request to my controller and within that request I'm sending a file and a list of objects.

 $.ajax({
            url: url,
            type: 'post',
            data: formData,
            processData: false,
            contentType: false,
            cache: false,
            success://some code
        })

I've took a look into my Request Payload using DevTools in Chrome, and it looks like this:

   Content-Disposition: form-data; name="firstPdf"; filename="blank.pdf"
    Content-Type: application/pdf

    Content-Disposition: form-data; name="myList"

    [{"key":"Section1","listTitles":["aaaa","aa","aa","a"]},
    {"key":"Section2","listTitles":["bb","b","bb","b"]}]

I'm retrieving the file okay in my controller action, but for some reason the list is always empty, this is my controller action:

 [HttpPost]
    public ActionResult LS10(HttpPostedFileBase firstPdf, List<PdfPieceVM> myList)
    {            
        var t = firstPdf.InputStream;         
        byte[] pdfByte = new byte[firstPdf.ContentLength];
        return File(pdfByte, "application/pdf", firstPdf.FileName);
    }

I've created a ViewModel just to get that list:

  public class PdfPieceVM
    {
        public string key { get; set; }
        public List<string> listTitles { get; set; }
    }

When I debug my code the myList parameter is always empty, but I'm receiving the file, what do I need to do to correct this?

AlexGH
  • 2,735
  • 5
  • 43
  • 76
  • 1
    Have you looked at this post yet: http://stackoverflow.com/questions/13242414/passing-a-list-of-objects-into-an-mvc-controller-method-using-jquery-ajax - Looks like contentType is required. – Alec Menconi May 10 '17 at 17:28

1 Answers1

0

Reading @Alex Menconi referenced post, I changed the controller action to retrieve a string and then deserialize it to the type that I wanted:

    [HttpPost]
        public ActionResult LS10(HttpPostedFileBase firstPdf, string myList)
        {
            List<PdfPieceVM> pdfPieces = new 
         JavaScriptSerializer().Deserialize<List<PdfPieceVM>>(myList);            
        }
AlexGH
  • 2,735
  • 5
  • 43
  • 76