0

I am try to upload files, need to pass files from ajax call to controller,but issue is i need to pass files along with model object ,which is creating issue. Please find the code as below:

//Step 1: All uploaded files
var files = $("#postedFile").get(0).files;
var fdata = new FormData();
for (var i = 0; i < files.length; i++) {
  fdata.append("files", files[i]);
};


//Step 2: Serialized form 
var ModelObject = $('#form').serializeObject();

//Step 3: Ajax call:
$.ajax({
  url: '/controller/actionname',
  data: fdata,
  dataType: "json",
  async: false,
  type: 'post',
  processData: false,
  contentType: false,
  success: function(response) {

  },

  error: function(xhr, ajaxOptions, error) {
    emailStatus = false;
  }
});
Karan
  • 12,059
  • 3
  • 24
  • 40
Nitin Soni
  • 11
  • 3

2 Answers2

1

First, use ajax to replace the original form submission method, you need to add event.preventDefault(); to the click event to prevent the default form submission method from occurring.

I am try to upload files, need to pass files from ajax call to controller,but issue is i need to pass files along with model object ,which is creating issue.

To solve it, you can use the following two methods to pass parameters by ajax:

  1. Use var fdata = new FormData($('#form').get(0)); to get all the model data in the form.

  2. Split the ModelObject as an array and then take fields by name and value one by one:

             var ModelObject = $('#form').serializeArray();
             for (var i = 0; i < ModelObject.length; i++) {
              fdata.append(ModelObject[i].name, ModelObject[i].value);
             }
    

Here is complete code:

Model:

public class UploadVm 
    { 
        public int ID { get; set; }
        public string Name { get; set; }
    }

Controller:

 [HttpPost]
    public IActionResult Index(IFormFile files, UploadVm model)
    {
        return View();

    }

View:

      <form id="form" method="post" enctype="multipart/form-data">
            ID:<input type="text" name="ID" id="id" /><br>
            Name:<input type="text" name="Name" id="name" /><br>
            File:<input type="file" id="postedFile" /><br>
            <input type="submit" name="submit" id="upload" value="Submit" />
        </form>


@section Scripts
{
    <script>
        $("#upload").click(function (e) {

            event.preventDefault();
            var files = $("#postedFile").get(0).files;
            var fdata = new FormData($('#form').get(0));//the first way
            for (var i = 0; i < files.length; i++) {
                fdata.append("files", files[i]);
            };
            
            //the second way 
            //var ModelObject = $('#form').serializeArray(); 
            //for (var i = 0; i < ModelObject.length; i++) {
            //    fdata.append(ModelObject[i].name, ModelObject[i].value);
            //}

            $.ajax({
                url: '/Home/Index',
                data: fdata,
                dataType: "json",
                async: false,
                type: 'POST',
                processData: false,
                contentType: false,
                success: function (response) {
                    console.log(response);
                },
                error: function (xhr, ajaxOptions, error) {
                    alert("error!");
                }
            });
        }); 
    </script> 
}

You can also refer to this.

Here is the test result:

enter image description here

LouraQ
  • 6,443
  • 2
  • 6
  • 16
0

Try like below.

  • Remove dataType: "json",, async: false,.
  • Update your fdata and append serializeObject, like fdata.append("model", ModelObject);.
  • Make sure your parameter names in action must match with files and model. These are the names you used with fdata.append.

Complete code will look like below.

//Step 1: All uploaded files
var files = $("#postedFile").get(0).files;
var fdata = new FormData();
for (var i = 0; i < files.length; i++) {
  fdata.append("files", files[i]);
};

//Step 2: Serialized form 
var ModelObject = $('#form').serializeObject();
fdata.append("model", ModelObject);

//Step 3: Ajax call:
$.ajax({
  url: '/controller/actionname',
  data: fdata,
  type: 'post',
  processData: false,
  contentType: false,
  success: function(response) {
    console.log(response);
  },
  error: function(xhr, ajaxOptions, error) {
    emailStatus = false;
  }
});
Karan
  • 12,059
  • 3
  • 24
  • 40