Search code examples
c#jqueryajaxasp.net-core-mvc

can I send a list of objects including images using FormData object from view to the controller by ajax call?


I have a list of forms including image files and collect them using jquery and try to send them to the controller, I tried to send one form that included an image, and working fine, but when I send the list, not work


Solution

  • Yes, you can send a list of objects including images using the FormData object from view to the controller by an AJAX call.

    To do this, you can create a new instance of the FormData object, append each form in the list to the FormData object, and then send the FormData object through an AJAX call to the controller.

    Here is an example that demonstrates how to do it:

    // Create a new instance of the FormData object
    var formData = new FormData();
    
    // Iterate over each form in the list
    $('form').each(function() {
    
      // Append the form data to the FormData object
      var form = $(this)[0];
      var formdata = new FormData(form);
      
      formData.append('forms[]', formdata);
    });
    
    // Send the FormData object through an AJAX call to the controller
    $.ajax({
      url: 'your_controller_url',
      type: 'POST',
      data: formData,
      contentType: false,
      processData: false,
      success: function(response) {
        // Handle the response from the controller
      },
      error: function(error) {
        // Handle any errors that occur during the AJAX call
      }
    });