A day with .Net

My day to day experince in .net

File upload with ASP.NET MVC and Jquery Form Plugin.

Posted by vivekcek on April 21, 2014

In this post, i will show you how to upload a file without a full postback using Jquery Form Plugin.
Jquery form plugin use ajax to upload the file. This technique will be more helpful when you need to upload file from a modal partial view.

Refer these scripts.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

Create a file input and a submit button.

@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    
    <input type="file" name="myfile"><br>
    <input type="submit" value="Upload File to Server">
}

Now create some div’s for progress bar and status

<div class="progress">
    <div class="bar"></div>
    <div class="percent">0%</div>
</div>
<div id="status"></div>

Now include this script in your view

<script>
    (function () {

        var bar = $('.bar');
        var percent = $('.percent');
        var status = $('#status');

        $('form').ajaxForm({
            beforeSend: function () {
                status.empty();
                var percentVal = '0%';
                bar.width(percentVal)
                percent.html(percentVal);
            },
            uploadProgress: function (event, position, total, percentComplete) {
                var percentVal = percentComplete + '%';
                bar.width(percentVal)
                percent.html(percentVal);
            },
            success: function () {
                var percentVal = '100%';
                bar.width(percentVal)
                percent.html(percentVal);
            },
            complete: function (xhr) {
                status.html(xhr.responseText);
            }
        });

    })();
</script>

Now write a save method in your controller

[HttpPost]
 public ActionResult Save(HttpPostedFileBase myfile)
      {
         return RedirectToAction("Index");
      }

One Response to “File upload with ASP.NET MVC and Jquery Form Plugin.”

  1. Thanks…a lot

Leave a comment