Search code examples
asp.net-mvc-4jquery-file-upload

Uploading file issue with asp.net mvc 4


I am learning ASP.NET MVC and I am confused between use of AJaxform or Jquery. With some answers on google I am able to understand that JQuery is a better option but still confuse why?

Here is my code for uploading file via JQuery, which is going to my controller but I am getting null for both HttpPostedFileBase file, CreatePost post

Model

 public class CreatePost
{
    public string userImage { get; set; }
}

Controller

 [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, CreatePost post )
        {
            var test = post.userImage;
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
                file.SaveAs(path);
            } 

            return RedirectToAction("Index");
        }

View

    <script type="text/javascript">
    $(function () {
        $('form').submit(function () {
            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            }
            return false;
        });
    });

</script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { nctype = "multipart/form-data" }))
{

     <div class="editor-label">
            @Html.LabelFor(model => model.userImage)
        </div>
        <input type="file" name="file"/>

    <input type="submit" value="OK" />
    <div id="result"></div>
}

Why I am getting null for file and post?


Solution

  • There are problems in uploading files in Ajax, I have figured that the problem is from form.Serialize() instead you can use FormData it as below:

    p.s. All versions of browsers doesn't support FormData

    <script type="text/javascript">
    $(function () {
        $('form').submit(function () {
            //Below line is added
            var formData = new FormData($('form')[0]);
            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    //Below line is changed
                    data: formData,
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            }
            return false;
        });
    });
    

    Also there is a typo in your form declaration change ncType to enctype

    if you are going to use JqueryDialog too, you can find this link useful for uploading files: Uploading file via Jquery ui dialog and Ajax [Resolved]