In my project, there is a form that renders from a partial view. I am looking to send both the form data and the selected file from the file control using an ajax call for form submission. Below is the code snippet that saves the selected file to a folder:
Below is the JavaScript function:
<script type="text/javascript">
$(function () {
$('#careerForm').submit(function (e) {
e.stopPropagation();
e.preventDefault();
var formData = new FormData();
var totalFiles = document.getElementById("fuUploadCV").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("fuUploadCV").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '/CareerSurface/UploadImage/', //put your controller/action here
data: formData,
dataType: 'json',
contentType: false,
processData: false,
beforeSend: function (xhr) {
//do something before send
},
success: function (data) {
//do something if success
},
error: function (data) {
//do something if error
}
});
});
});
</script>
Here is the HTML:
using (Html.BeginForm("ApplyNow", "CareerSurface", FormMethod.Post, new { enctype = "multipart/form-data", autocomplete = "off", id ="careerForm" })){
<div class="Field-Label-Box">
<label>First Name:<span> *</span></label>
</div>
<div class="Field-Value-Box">
@Html.TextBoxFor(model => model.FirstName, new { id = "txtFirstName", name = "txtFirstName", required = "required" })
@Html.ValidationMessageFor(model => model.FirstName)
</div>
......
<div class="Field-Label-Box">
<label>Upload CV:<span> *</span></label>
</div>
<div class="Field-Value-Box">
@Html.TextBoxFor(model => model.ResumeUpload, new { type = "file", id = "fuUploadCV", name = "fuUploadCV", required = "required" })</div>
<input type="submit" id="btnSave" value="Submit" name="btnSave" />
}
c# :
[HttpPost]
public void UploadImage()
{
if (Request.Files.Count > 0)
{
dynamic file = Request.Files[0];
//do something with your 'file'
}
}
The current setup works well for sending only the selected file. However, I now need to also send all other data (model class object) to the same controller method. I have attempted using JSON but encountered an 'Illegal Invocation' error.
If you have any suggestions on how to pass both sets of data to the single method, please let me know. Feel free to ask if you have any questions. I appreciate any help as I am currently stuck at this point.
Thank you.