On several pages of my web site (ASP.Net MVC, jQuery, KendoUI SPA), I have a modal window to upload a file.
addAttachment: function (e) { $("form").on("submit", function (event) { event.preventDefault(); }); e.preventDefault(); var formData = new FormData($("#formUpload")[0]); var url = 'api/Attachments/UploadAttachment'; app.postFile(url, formData, function (statusCode) { if (statusCode === 201) { // File was created -- do stuff } }); },
<div id="addAttachmentWindow" data-role="window" data-height="300px" data-width="600px" data-modal="true" data-title="Add Attachment" data-visible="false"> <div class="row"> <form id="formUpload" class="form-horizontal"> <input type="hidden" id="hdnRecordId" name="recordId" data-bind="value: object.id" /> <div class="form-group"> <label class="col-sm-4 control-label" for="txtDocumentTitle">Title</label> <div class="col-sm-6"> <input name="documentTitle" id="txtDocumentTitle" type="text" class="k-textbox" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="fuFileInput">Document</label> <div class="col-sm-6"> <input id="fuFileInput" name="files" type="file" /> </div> </div> <div class="col-sm-6 col-sm-offset-6"> <button data-role="button" data-icon="plus" data-bind="click: addAttachment">Add Attachment</button> </div> </form> </div> </div>
With the code for postFile
var postFile = function(uri, formData, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr.status);
}
};
xhr.open('POST', uri);
xhr.setRequestHeader("RequestVerificationToken", antiForgeryToken);
xhr.send(formData);
};
Most of the pages, this works fine, But on a couple of pages, it will issue the POST, without the form fields and immediately issue a GET for
/?recordId=1&documentTitle=documentTitleInput&files=FileNameHere.pdf
which goes to the Home Controller's Index function. If I go to one of the pages with this issue, do a Shift-Reload, and try the upload it will work as expected, the form fields are intact, and the callback is called.
Issues
I've tried creating an empty FormData, and appending the values to it, and played everything I can find to stop the normal submit event from happening ( e.preventDefault()
, e.stopPropogation()
, return false
etc.);
ok so some reading on the subject and its because the prevent default only works on elements, not on a form submit event, which is what your using...
create two submit inputs... one a button, the other a hidden input.. like so ..
<button type="button" id="submit">Submit</button>
<input style="display: none;" type="submit" id="realsubmit">
then do your jquery like so ...
$("#submit").on('click', function() {
//do stuff
$("#realsubmit").trigger('click');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.