Domanda

I'm attempting to post some files I collect on a page to my ASP.Net MVC5 controller. I'll show you my request object that I'm expecting, and the front-end code I use to post the request.

When it comes to the controller, the CoverSheet does come through, however no matter what I do, the SupportingDocuments array is always null. I tried using FormData and I tried just using a normal JS object, both with the same results.

public class SomeRequest
{
    public int SomeRequestId { get; set; }
    public HttpPostedFileBase CoverSheet { get; set; }
    public HttpPostedFileBase[] SupportingDocuments { get; set; }
}

And here's the front-end

var formData = new FormData();
var supportingDocsArray = [];
_.each(supportingDocumentsInput[0].files, function(f) { supportingDocsArray.push(f); });
formData.append('SomeRequestId', self.selectedThing().SomeRequestId);
formData.append('CoverSheet', coverSheetInput[0].files[0]);
formData.append('SupportingDocuments', supportingDocsArray);
var request = $.ajax({
    url: '/SomeController/Upload',
    data: formData,
    type: 'POST',
    dataType: 'json',
    processData: false,
});

So as you can see, I'm expecting both a single file in the CoverSheet and a possible array of files in the SupportingDocuments.

When it comes to the controller, the CoverSheet does come through, however no matter what I do, the SupportingDocuments array is always null.

Any tips to get this working?

Thanks and have a great day.

È stato utile?

Soluzione

Looks like the best way to fix this was to not expect the array to come in on the request object.

Here's the updated controller code:

        public async Task<JsonNetResult> Upload(ThingUploadRequest req)
    {
        foreach (string filename in Request.Files)
        {
            var file = Request.Files[filename];
            if (file != req.CoverSheet)
            {
                req.SupportingDocuments.Add(file);
            }
        }

        var result = await _uploadHandler.Upload(req);
        return new JsonNetResult
        {
            Data = result
        };
    }

and here's the updated front-end code:

                var formData = new FormData();
                _.each(supportingDocumentsInput[0].files, function(f) {
                    formData.append(f.name, f);
                });
                formData.append('SomeThingId', self.selectedThing().ThingId);
                formData.append('CoverSheet', coverSheetInput[0].files[0]);
                var request = $.ajax({
                    url: '/SomeController/Upload',
                    data: formData,
                    type: 'POST',
                    dataType: 'json',
                    processData: false,
                    contentType: false
                });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top