Originally posted on: http://geekswithblogs.net/rgupta/archive/2014/06/23/calling-a-success-callback-jquery-function-after-file-upload-in.aspx
Many a times there is a need to call a function after successfully uploading a file in MVC using form submit.
Thus your HTML code will look something like the following for uploading a file:
1<form class="item-add" action='@Url.Action("UploadDocument", "Upload", new { area = "Masters" })' enctype="multipart/form-data" id="ImgForm" method="post" name="ImgForm" target="UploadTarget" novalidate="novalidate">2<input type="hidden" id="uploadFileFormat" name="uploadFileFormat" value=""/>3<input type="hidden" id="ImagePath" name="ImagePath" value="@Model.ImagePath"/>4<input tabindex="3" type="file" id="imageMasterDetails" name="imageMasterDetails">5<input tabindex="6" type="button" value="Upload"class="btn primary save" onclick="UploadImage()">6</form>7<iframe id="UploadTarget" name="UploadTarget" style="position: absolute; left: -999em; top: -999em;"></iframe>8
The Javascript code will be something like the following:
1 function UploadImage() {2 $("#ImgForm").submit();3 SCM.displaySuccessMessage('#UploadMasterSuccess', $.common.uploadMaster.successMessage);4 someCallbackFunctionAfterSuccessfulFileUpload();5 }
The problem with the above code is that, the “someCallbackFunctionAfterSuccessfulFileUpload()” gets called immediately and not after the successful upload of the file.
Inorder to fix this we need to use the jquery.form.js plugin available here : http://malsup.github.io/jquery.form.js
The modified javascript will looks something like the following (note that the above jquery.form.js file has been included at the top of the CSHTML file) :
11<script src="~/Scripts/jquery.form.js"></script> 22<script type="text/javascript"> 33 $(function () { 44 var options = { 55 beforeSubmit: function (formData, jqForm, options) { }, // pre-submit callback 66 success: function (responseText, statusText, xhr, form) { 77 88 SCM.displaySuccessMessage('#UploadMasterSuccess', $.common.uploadMaster.successMessage); 99 someCallbackFunctionAfterSuccessfulFileUpload();1010// post-submit callback 1111 };1212// bind form using 'ajaxForm' 1313 $('#ImgForm').ajaxForm(options);14141515 var UploadImage = function(){1616///same javascript code as before1717 $("#ImgForm").submit();1818 }19192020 });2121</script>
Now the someCallbackFunctionAfterSuccessfulFileUpload() function will get called only after successful upload of the image.
For credits, i found the solution here : http://stackoverflow.com/questions/12940535/how-to-upload-files-in-mvc