I have a form which has some input fields and a file upload.
<form id="documentUploadForm" method="post" enctype="multipart/form-data">
<input type="text" id="name"></input>
<input type="radio" id="type1"></input>
<input type="radio" id="type2"></input>
<input type="date" id="date"></input>
<input type="file" id="documentToUpload"></input>
<input type="submit" id="Save" value="Upload"></input>
</form>
I need to post the form along with the uploaded file to my controller action. Below is my jquery script to do that.
$('#Save').click(function(){
var formData = new FormData();
var file = $('#documentToUpload').get(0).files[0];
if (file.length > 0) {
formData.append("File", file, 'document');
}
var data = $('#documentUploadForm').serialize();
formData.append("Form", data);
$.ajax({
type: 'Post',
url: url,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function (response) {
//do something
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Fail!");
}
});
})
But this does not seem to work. The form collection posted to my controller is always null.
[HttpPost]
public JsonResult Upload(FormCollection form)
{
}
How do I post the form and the uploaded file and receive it in my action method?