Search code examples
jqueryasp.net-mvcform-data

Posting File and List to MVC controller Using FormData MVC


I am trying to post a file and a list to an MVC controller using FormData but the list seems to be empty on hitting the controller.

Form Data:

 var formData = new FormData();

                formData.append("AttachedFile", files[0]);
                formData.append("Items", invoice.serialize());
                formData.append("CustomerId", 1);
                formData.append("RevenueHeadId", demandNoteObject.RevenueHeadId);

Model:

  public int CustomerId { get; set; }
    public int RevenueHeadId { get; set; }
    [DataType(DataType.Upload)]
    public HttpPostedFileBase AttachedFile { get; set; }
    public List<Items> Items { get; set; }

Controller:

[HttpPost]
    public ActionResult Create(InvoiceCreateModel model)

JQuery:

  $.ajax({
                    type: "POST",
                    url: "@Url.Action("Create", "")",
                    datatype: "Json",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {

Solution

  •  $.ajax({
                type: 'POST',
                url: '@Url.Action("Create", "yourControllerName")',
                data: formData,
                contentType: false,
                processData: false,
                success: function (data) { ...}
            });
    

    try this

    Edit Because Items is a collection of objects, you have to add each one of them with an index

    var index = 0;
    for(var item of invoice){
        var pair = item[key];
        formData.append("Items[" + index + "].yourField", pair.yourField);
        index++;
    }