1

Below is the razor code when I'm returning the form to the jquery function on submit.

 @model Slider
    @{

         Layout = null;
     }

    @using (Html.BeginForm("AddOrEdit", "Slider", FormMethod.Post, new { enctype  = "multipart/form-data" , onsubmit = "return   SubmitForm(this)" }))
    {
      @Html.HiddenFor(m => m.Id)



     <div class="form-group" style="height:270px;">
      @Html.LabelFor(m => m.ImageFile, new { @class = "blue-text", @style = 
      "font-size:16px", @id = "" })

 <input name="ImageFile" type="file"  />

 </div>

<div class="form-group">
     <input type="submit" value="Submit" class="btn btn-primary" />
     <input type="reset" value="Reset" class="btn" />
 </div>
 }

The Jquery function ain't able to serialize the input file type and send it to the controller unless I change it to json . But if I would change it to json I won't get the validation

  function SubmitForm(form) {
        debugger;
        $.validator.unobtrusive.parse(form);
        debugger;
        if ($(form).valid()) {
            debugger;
            $.ajax({
                type: "POST",
                url: form.action,
                //"datatype": "json"
                data: $(form).serialize(),
                success: function (data) {
                    if (data.success) {
                        Popup.dialog('close');
                        dataTable.ajax.reload();

                        $.notify(data.message, {
                            globalPosition: "top center",
                            className: "success"
                        })

                    } else {
                        Popup.dialog('close');

                        $.notify(data.message, {
                            globalPosition: "top center",
                            className: "error"
                        })
                    }
                }
            });
        }
        return false;
    }
Maho
  • 35
  • 1
  • 6

1 Answers1

12

Try below code and make few changes in ajax code. Add below parameters in your code.

processData: false,
contentType: false,

And add var formData = new FormData($("#formID")[0]); line before ajax starts.

You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value. You can use below code for uploading files using AJAX.

var formData = new FormData($(form)[0]);
$.ajax({
    url: form.action,
    type: form.method,
    data: formData,
    processData: false,
    contentType: false,

    success: function (response) {

    }
});
Pankaj Makwana
  • 3,030
  • 6
  • 31
  • 47