Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume

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) :

1 1 <script src="~/Scripts/jquery.form.js"></script> 2 2 <script type="text/javascript" > 3 3 $(function () { 4 4 var options = { 5 5 beforeSubmit: function (formData, jqForm, options) { }, // pre-submit callback 6 6 success: function (responseText, statusText, xhr, form) { 7 7 8 8 SCM.displaySuccessMessage('#UploadMasterSuccess', $.common.uploadMaster.successMessage); 9 9 someCallbackFunctionAfterSuccessfulFileUpload(); 10 10 // post-submit callback 11 11 }; 12 12 // bind form using 'ajaxForm' 13 13 $('#ImgForm').ajaxForm(options); 14 14 15 15 var UploadImage = function(){ 16 16 ///same javascript code as before 17 17 $("#ImgForm").submit(); 18 18 } 19 19 20 20 }); 21 21 </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

Posted on Monday, June 23, 2014 5:40 AM | Back to top


Comments on this post: Calling a success Callback Jquery function after File Upload in MVC

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Rohit Gupta | Powered by: GeeksWithBlogs.net