Pinakin Shah
Pinakin Shah

Reputation: 877

Posting viewModel and upload files with asp.net mvc 3 and knockoutjs

We are submitting an asp.net mvc view form using the knockoutjs postJson util. All works fine but now we want to add a file upload option in the form.

As per Uploading file in asp.net mvc, we added the elements and the enctype="multipart/form-data" attribute in the Form but we do not get any files in the Request.Files collection in the Controller

Is there any issue using ko.utils.postJson? Is there any better way to upload files along with my form data?

  1. All my elements are using KO binds so cannot remove knockout
  2. We used postJson so that it can simulate a form submission and the controller can redirect to another view

Upvotes: 3

Views: 4302

Answers (1)

Paul Tyng
Paul Tyng

Reputation: 7584

The postJson src is doing a JSON.stringify on each input it creates and inserting it as an input element in to an internal form element:

for (var key in data) {
    var input = document.createElement("INPUT");
    input.name = key;
    input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
    form.appendChild(input);
}

As such, file data from a file input cannot be loaded via javascript to be posted via the postJson call as it currently exists so your best bet for that would be to just upload the files and post the JSON in two separate requests. It may also be possible to inject the file input into this form the postJson method creates (by overriding the method) but its kind of hacky and may not be forward compatible.

Upvotes: 1

Related Questions