Using Ajax to submit form data including files
$(document).ready(function() {
$(form)
.formValidation({
... options ...
})
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="uploadedFiles"]')[0].files;
$.each(files, function(i, file) {
// Prefix the name of uploaded files with "uploadedFiles-"
// Of course, you can change it to any string
formData.append('uploadedFiles-' + i, file);
});
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
// Process the result ...
}
});
});
});
Please pay attention on contentType and processData options of the jQuery's ajax() method:
Setting contentType: false tells jQuery to not add Content-Type to the request
Setting processData: false tells jQuery to not convert our data (which is a FormData instance) to a string
On the server side, you can get the uploaded files under the names uploadedFiles-0, uploadedFiles-1, and so forth, depending how many files are chosen.
FormData are supported in modern browsers including IE 10+. You shouldn't use it if your application needs to support previous versions of IE such as IE 8, IE 9.
To pass objects or collections as additional data in the upload event. ( async)
function upload(e) {
var additional = '@Html.Raw(Json.Encode(Model))';
e.data = JSON.parse(additional);
}
Then in the Controller Action you could get the model as additional parameter..
public ActionResult Save(IEnumerable<HttpPostedFileBase> files, ModelType additional)
{ }