I am using jQuery File Upload to asynchronously upload images to a .NET MVC controller. I have the following script that runs
<script type="text/javascript">
$('#Image').fileupload({
url: "/Home/PostUpdate",
dataType: 'json',
replaceFileInput: false,
dropZone: null,
autoUpload: false,
maxNumberOfFiles: 1,
maxFileSize: 2000000,
add: function (e, data) {
$("form").submit(function (event) {
event.preventDefault();
console.log("posting from jquery file upload");
if ($("#Image")[0].files[0].size > 0 && ($("#PostText").val() === "" || $("#PostText").val() === undefined)) {
// Warning message here
}
else {
console.log("2a");
data.submit();
}
});
},
done: function (e, data) {
// Done code here...
}
});
$("form").submit(function (event) {
event.preventDefault();
if ($("#Image")[0].files[0] == undefined) {
console.log("posting from default ajax");
var url = "/Home/PostUpdate/";
$.ajax({
url: url,
datatype: "json",
data: $(this).serialize(),
cache: false,
type: "POST",
success: function (data) {
// Success code here
},
error: function (response) {
alert("error");
}
});
}
});
</script>
My HTML is a standard <input type="file"/>
, and so I can attach a file and upload and I see the file go through to the server-side code. I process, and add to the database, without issue.
The first image I select, uploads once. If I then choose a second image and upload, it performs the upload and hits the MVC controller twice. If I choose a third image, the upload happens three times? It always hits the same data.submit()
namely the one that occurs at console.log("2a")
but I am at a loss as to why it would occur multiple times?
I'm wondering if the event.preventDefault() is causing this to fire? But that wouldn't make sense as to why I get three, then four, then five posts to the controller action?
Has anyone else had this and if so, what did you implement to fix it?
Thanks in advance!