Naveen
Naveen

Reputation: 159

Post modelcontaining HttpPostedFileBase file along with some parameters using form.serialize() in mvc4

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 ??

Upvotes: 2

Views: 3052

Answers (1)

Tobias
Tobias

Reputation: 2840

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.

Upvotes: 2

Related Questions