0

I am trying to post the values to the controller via ajax post. Here my problem is I am using Serialize method to post the form values. I have to send Images as well. How can I send images and form data and what should be the controller method that accepts both files and model values?

I am getting all the text values like this

var files = $("#formid").serialize();

I am getting images like this

 var form1Data = new FormData();
 var totalFiles = document.getElementById("files").files.length;
  for (var i = 0; i < totalFiles; i++) {
        var file = document.getElementById("files").files[i];
        form1Data.append("files", file);
  }

In ajax call I have to send both files and formdata. How to send in the ajax call

 $.ajax(
         {
             url: "/Home/PostanAd/",
             type: "POST",                  
             data: { form1Data: form1Data, files: files },
             contentType: false,
             processData: false,
         });

can some one please suggest the answer?

Pawan
  • 1,704
  • 1
  • 16
  • 37
win2
  • 11
  • 4
  • 1
    possible duplicate of [how to append whole set of model to formdata and obtain it in MVC](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc) –  Aug 22 '15 at 09:26

1 Answers1

0
var formData = new FormData();

//For each your form inputs use this line

form_data.append("name1", $("#id1").val());

//Now Add All Images to Form Data object

var totalFiles = document.getElementById("files").files.length;
for (var i = 0; i < totalFiles; i++) {
    var file = document.getElementById("files").files[i];
    formData.append("files[]", file);  //Use [] to add multiple.
}

//Then just make simple ajax call with data : formData only

$.ajax(
            {
                url: "/Home/PostanAd/",
                type: "POST",

                data: formdata,
                contentType: false,
                processData: false,
Vishal Rambhiya
  • 741
  • 6
  • 10
  • how can i get values in the model ? or should i use httppostedfilebase?? – win2 Aug 22 '15 at 09:49
  • you can use $_FILE to read uploaded files. and run for loop for accessing all files – Vishal Rambhiya Aug 22 '15 at 10:08
  • @user3518928, Did you even look at the link I gave you above? Its just `var formdata = new FormData($('form').get(0));` and `data: formdata,` (one line of code serializes all you form values and all the files!) –  Aug 22 '15 at 10:32