Sending an array or list of files from AJAX to the Controller

I have a task to upload multiple files and pass them to my Controller's Action. The current code is functional, but I feel there could be room for improvement as it's somewhat manual.

I need to display file upload elements based on the number of records fetched from the database. The number of records varies, ranging from 1 to possibly more than 10.

HTML Code

@{
    foreach(FileModel fileModel in Model.FileModel)
    {
        <input type="file" id="@("originalFile" + i)" />
    }
}

AJAX Code

for(i = 1; i <= @Model.FileModel.Count; i++)
{
    if($("#originalFile" + i).val() == "")
    {
        alert("You must upload all files");
        return false;
    }
    else
        model.append("originalFile" + i, $("#originalFile" + i)[0].files[0]);
}

C# Code [HttpPost]

public ActionResult UploadFiles(string masterRecordID, HttpPostedFileBase originalFile1 = null, HttpPostedFileBase originalFile2 = null, HttpPostedFileBase originalFile3 = null, HttpPostedFileBase originalFile4 = null, HttpPostedFileBase originalFile5 = null)
{

}

The code above is not efficient as I am manually passing individual files. The number of files can vary, so how can I make it dynamic by somehow passing an array or object of files through AJAX and then handling them in the controller?

Answer №1

It turns out that the answer by @QingGuo, which was initially deleted, actually holds true in terms of the concept.

To enable support for multiple files, you will need to make a modification to your UploadFiles API action by changing the originalFiles parameter to an array or list.

public ActionResult UploadFiles(string masterRecordID, HttpPostedFileBase[] originalFiles)

Additionally, in your JavaScript section:

model.append("originalFiles", $("#originalFile" + i)[0].files[0]);

https://i.stack.imgur.com/oKnEI.gif

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve and delete a row based on the search criteria in an HTML table using jQuery

Here is the HTML code snippet: <table class="table" id="myTable"> <tr> <th>Type</th> <th>Counter</th> <th>Remove</th> <th style="display:none;">TypeDistribution</t ...

Condensed JQuery condition code for "if" statement

This piece of code is designed to sequentially display 10 questions and control the visibility of each question using the CSS class .hideme. It also sends metrics data to Google Analytics. Although it functions properly, I feel like the code is too leng ...

Calculating the sum of all words that have been successfully finished

My spelling game includes words of different sizes ranging from 3 to 6 letters. Once a certain number of words are completed in the grid, the remaining grid fades away. Instead of only considering one word size at a time, I want the game to calculate the t ...

Azure Function: Eliminate duplicate data in JSON from two many-to-many relationships into a single table

I am facing an issue where I have multiple many-to-many tables mapping to a single table, resulting in duplicate data that needs to be removed from the JSON output. Additionally, the Ingredients and Conditions are displayed as lists, causing duplication of ...

Can I use javascript/jquery to alter the direction of text in each line?

Looking for assistance with changing text direction on each new line. For instance: text left-to-right text right-to-left text left-to-right text right-to-left... etc. I would like the text direction to change with each word-wrap: break-word. Any help w ...

The target for ajaxSubmit is being duplicated instead of being replaced

I encountered a problem with the code below: $('#refresh').click(function () { alert($('.report-container').length); $('.report-container').each(function () { var accordian = this; var url = $(this) ...

Semantic UI Troubles: Unraveling the Sidebars and #pusher Defects

Hey there, I could really use some assistance with an issue I'm facing. I have this particular structure that's causing me trouble. <div id="toolbar" class="toolbar overlay-displace-top clearfix toolbar-processed"> ... </div> < ...

Retrieving Browser URL using Node.js

Currently, I am trying to extract the browser URL from a user who has integrated my external JavaScript file into their website. The process involves them including the JS file, which triggers an Ajax call using jQuery to communicate with my Node server. ...

There seems to be a problem with the full calendar updateEvent feature as it is unable to read the property 'clone'

Struggling to update an event using FullCalendar and a modal. Encounter the 'cannot read property 'clone' of undefined' error when attempting to update. Following the documentation, I utilize the clientEvents method. It is crucial t ...

What could be the reason for multer functioning properly with PNG and JPG files, but encountering issues with WebP files in my setup using Tsed, Express

I previously had my endpoint set up to handle png and jpg files successfully. However, I wanted to restrict it to only allow webp files. So, I updated the file filter callback accordingly. Unfortunately, now Multer does not save any files other than png or ...

Is it possible to create a button that can bring in a .css file?

Is there a way to create a button that imports styles from a .css file, or is it possible to change multiple CSS properties with buttons to create different website themes? This is the CSS file I have: .body { background-image: url("example.png"); } ...

Issues with Chrome causing Ajax synchronous requests to fail

Is the latest release of Chrome no longer supporting Synchronous Ajax calls? We're encountering an error with our Synchronous Ajax requests after updating to version 73.0.3683.103. Interestingly, Synchronous calls are still functioning properly on Fir ...

Is there a way to send HTML element values to a MySQL Database in Django using Ajax without utilizing a form?

As a Django newcomer, I am currently encountering an issue with posting HTML tag data into the database. I have implemented a "PICK CASE" button that, when clicked, should pass the user_id (hidden in an HTML tag with display:none) and case_id from the tag ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

Are you ready to dive into the world of running an ASP.NET MVC project with Angular in Visual Studio

Currently, I am working on developing a CRUD application using ASP.NET MVC in Visual Studio with Angular. I am interested in running the entire project solely through VS Code without relying on Visual Studio. Does anyone have a solution for achieving thi ...

Turn off scroll bar to create a seamless browsing experience on your website

As I work on creating the frontend for a single-page website with seamless scrolling between divs, I'm looking to eliminate mouse scrolling altogether. I understand that using overflow:hidden; can hide scroll bars, but my goal is to make the page scr ...

How can I stretch a background image using jquery to cover the entire document instead of just the window

I have implemented a plugin called https://github.com/srobbin/jquery-backstretch to effectively stretch the background image. The problem arises when the content of the page is long enough to create a scrollbar. In this case, while scrolling, the backgrou ...

Recognizing Components in Alert using selenium webdriver in C#

I'm facing a challenge on this webpage where there is an alert that contains elements requiring interaction beyond the usual Accept() or Dismiss(). For instance, a datagrid, another button. Any ideas on how to tackle this? ...

Can you recommend any open source projects with exceptionally well-written Jasmine or Jasmine-Jquery tests?

Currently, I am in the process of learning how to test a new jquery plugin that I plan to develop. I'm curious if there are any notable Github projects like Jasmine or Jasmine-jquery with impressively crafted Jasmine tests that I could explore for in ...

What could be causing jQuery to overlook dynamically loaded jQuery Mobile buttons?

While working with a web page that uses jQuery Mobile, I utilized Ajax to load the following HTML content. The key detail is the presence of the onButton class attached to the anchor tag. <a class="onButton ui-btn ui-btn-inline ui-btn-corner-all ui-sha ...