2

I have a ViewModel containing some string and HttpPostedFileBase properties . When i am posting the model to the controller using below ajax call,

 $.ajax({
                url: '@Url.Action("_AddFeedback", "Mcq")',
                type: 'post',
                 data: $('form#frm-feedback').serialize(),
              //  data: formData,

                success: function (data) {
                    alert("done");
                },
                error: function (data) {
                    alert("Error occured while saving Option's data.");
                }
            });

I am getting value for string but null for HttpPostedFileBase type properties. How can we post HttpPostedFileBase file using ajax ??

tereško
  • 58,060
  • 25
  • 98
  • 150
Naveen
  • 149
  • 1
  • 2
  • 13

1 Answers1

2

Unfortunately, you cannot send files with AJAX, when serializing the form, but luckily there is another way, if you don't mind using HTML5. A short example, as per this answer:

Markup:

<form id="upload-form" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" id="submit" value="Upload" />
</form>

Javascript:

$('#submit').click(function (e) {
    e.preventDefault();
    var formData = new FormData($('#upload-form')[0]);
    $.ajax({
        url: '@Url.Action("_AddFeedback", "Mcq")',
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
});

As stated, this is an HTML5 approach, which means it won't necessarily work in every browser. If this is a problem, see the thread I've linked to for other approaches to this problem.

Community
  • 1
  • 1
Tobias
  • 2,811
  • 2
  • 20
  • 31
  • Naveen said :ViewModel containing some string and HttpPostedFileBase properties. so it's not just HttpPostedFileBase property.also @Naveen wants to serialize the form not append them to FormData. – fbarikzehy Mar 30 '16 at 10:56