What is the best way to include and transmit multiple records in ASP.NET MVC with the help of jQuery?

Having trouble sending multiple records to the database using JavaScript in ASP.NET MVC? Look no further, as I have the best code that can send data to the controller. However, the file attachment is not being sent along with it.

I've tried various methods and came across FormData as one potential solution, but I'm having difficulty implementing it in this scenario.

Controller:

public ActionResult SaveAllFeedback(FEEDBACKVM[] fEEDBACKs)
        {
            try
            {
                if (fEEDBACKs != null)
                {
                    FEEDBACK fEEDBACK = new FEEDBACK();
                    foreach (var item in fEEDBACKs)
                    {
                        fEEDBACK.DATE = item.DATE;
                        fEEDBACK.COMMENT = item.COMMENT;
                        fEEDBACK.STUDENTID = item.STUDENTID;
                        fEEDBACK.TEACHERID = db.TEACHERs.Where(x => x.EMAIL == User.Identity.Name).FirstOrDefault().ID;
                        if (item.HOMEWORK != null)
                        {
                            fEEDBACK.HOMEWORK = SaveToPhysicalLocation(item.HOMEWORK);
                        }
                        db.FEEDBACKs.Add(fEEDBACK);
                    }
                    db.SaveChanges();
                    return Json("Done", JsonRequestBehavior.AllowGet);
                }
                return Json("Unable to save your feedback! Please provide correct information", JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json("Unable to save your feedback! Please try again later.", JsonRequestBehavior.AllowGet);
            }
        }


ViewPage:

<form>
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        <div class="form-group">
            <input name="DATE" id="DATE" type="date" class="form-control" />
        </div>

        <table class="table table-responsive table-hover" id="table1">
            <thead>
                <tr class="bg-cyan">
                    <th></th>
                    <th>RollNumber</th>
                    <th>Comment</th>
                    <th>Homework</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in ViewBag.students)
                {
                    <tr>
                        <td>
                            <input name="STUDENTID" type="text" value="@item.Key" hidden="hidden" />
                        </td>
                        <td>
                            <input name="STUDENTROLLNUMBER" type="text" value="@item.Value" class="form-control" readonly="readonly" />
                        </td>
                        <td>
                            <input name="COMMENT" type="text" class="form-control" />
                        </td>
                        <td>
                            <input name="HOMEWORK" type="file" class="form-control" />
                        </td>
                    </tr>
                }
            </tbody>
        </table>

        <div class="form-group">
            <div class="col-md-10">
                @Html.ValidationMessage("ErrorInfo", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button id="saveButton" type="submit" class="btn btn-danger">Save Attendance</button>
            </div>
        </div>
    </form>



Script:

<script>

           //After Click Save Button Pass All Data View To Controller For Save Database
            function saveButton(data) {
                return $.ajax({
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    type: 'POST',
                    url: '@Url.Action("SaveAllFeedback", "Teacherss")',
                    data: data,
                    success: function (result) {
                        alert(result);
                        location.reload();
                    },
                    error: function () {
                        alert("Error!")
                    }
                });
            }
            //Collect Multiple Order List For Pass To Controller
            $("#saveButton").click(function (e) {
                e.preventDefault();


                var formData = new FormData();

                var arr = [];
                arr.length = 0;

                $.each($("#table1 tbody tr"), function () {
                   //arr.push({
                   //     //DATE: $("#DATE").val(),
                   //     //STUDENTID: $(this).find('td:eq(0) input').val(),
                   //     //COMMENT: $(this).find('td:eq(2) input').val(),
                   //     //HOMEWORK: $(this).find('td:eq(3) input').val()
                   // });

                    formData.append("DATE", $("#DATE").val());
                    formData.append("STUDENTID", $(this).find('td:eq(0) input').val());
                    formData.append("COMMENT", $(this).find('td:eq(2) input').val());
                    formData.append("HOMEWORK", $(this).find('td:eq(3) input')[0].files[0]);


                });

                var data = JSON.stringify({
                    fEEDBACKs: formData
                });

                $.when(saveButton (data)).then(function (response) {
                    console.log(response);
                }).fail(function (err) {
                    console.log(err);
                });
            });

        </script>

I'm determined to successfully send multiple records, including files, to the database.

Answer №1

Are you absolutely certain that you wish to send the files? If so, then

Your form tag should appear as follows

<form id="yourid" action="youraction" enctype="multipart/form-data">
  Form Component
</form>

IMPORTANT NOTE: The `enctype="multipart/form-data"` attribute is crucial

Next, your controller should look something like this

public ActionResult YourController(FormCollection data)
{
    if (Request.Files.Count > 0)
    {
        foreach (string fileName in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[fileName];
            // You can save the file using this method
            string path = Server.MapPath("~/Yourpath/FileName" + fileName.Substring(fileName.LastIndexOf('.')));
            file.SaveAs(path);
            // Alternatively, you can load it into memory like this
            MemoryStream ms = new MemoryStream();
            file.InputStream.CopyTo(ms);
            // Use it as needed
        }
    }            
    return View();
}

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

Guide to showing the username on the page post-login

My MongoDB database is filled with user information. I'm looking to create a feature on the webpage that displays "Logged in as username here" at the top once users log in. My CSS skills are strong, but when it comes to JavaScript, I'm struggling ...

What is the process for adjusting the form transition?

I am currently working on a form that has a transition effect However, I encountered an issue: check out the problem here My goal is to keep the magnifying glass fixed in place while the form moves Here is a snippet of my code: import Search fro ...

Updating content on a webpage via AJAX request without altering the original source code

Within the body of our document, referred to as "form.php," we have the following components: At the head section, there is a JavaScript code block: <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").i ...

What could be the reason behind Next.js attempting to import a non-existent stylesheet?

Lately, I've come across an issue where Nextjs is attempting to import a non-existent stylesheet (refer to the images below). I'm looking for guidance on how to resolve this error. Hoping to find a solution here, thank you Web browser console W ...

Guy discussing the ins and outs of JavaScript variables

I am facing an issue with retrieving the value in the jQuery script. The value should be taken from route_path_images, but it's not showing up. var route_path_images="http://www.domain.com" jQuery("#header_background_night_star").fadeIn(2000).css("b ...

Implementing JSON responses in Express JS

My apologies for any language errors as English is not my first language, I am using Google Translate :) I have a question.. Here is the MySQL Query I am working with: SELECT destinations.*, questions.*, answers.* FROM destinations INNER JOIN questions ...

Dynamic scrolling text for overflowing text display

Here's a scenario I'm facing: Let's say I have three div tags, each 100 pixels wide: <--- DIV WIDTH ---> Text in div 1 Text in div two, it overflows Text in div three <--- DIV WIDTH ---> Currently, I've set the following C ...

Dynamic Rendering of Object Arrays in Table Columns using JavaScript

In the process of developing an appointment slot selection grid, I have successfully grouped all appointments by dates. However, I am facing challenges in displaying this array of Objects as a clickable grid with columns. The current output can be viewed h ...

Using Node.js to convert a file name to a timestamp

I need to change a filename into a timestamp in my Laravel application. let test = "/2020-05-16_11-17-47_UTC_1.jpg" I attempted using split and join to replace the -, but I don't believe it's the most efficient method. The desired output should ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...

Learn how to easily access a PDF report from a report viewer using AJAX within an ASP.NET MVC application

I need help with printing a PDF file from my application (rdlc report) by displaying it in the browser without downloading via Ajax. I have tried to open the file using the <a> tag (<a href="~/.../" target="_blank">print </a>) within an A ...

Creating a complete webpage using HTML

Is there a method to load an HTML file and execute the embedded javascript to create a complete HTML page programmatically similar to how browsers do? Edit 1 - I am working on an application where I need to extract data from an HTML page on a remote websi ...

I'm receiving a TypeError in Nodejs indicating that the hashPassword function is not recognized as a function. Can anyone offer advice on how to

How's everything going? I could really use your assistance! I'm currently working on developing an API for registering authenticated users, with data storage in the MongoDB Atlas database (cloud). Unfortunately, I've run into a troubling er ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

Get the top retweeted tweets associated with a specific keyword

There was a discussion on the same topic over at StackOverflow a while back, but unfortunately it didn't get any answers and was specifically focused on hashtags. So, I decided to bring up the question again: I'm interested in finding a way to r ...

What's causing my variables to be returned as null in the alerts?

Why am I receiving null values when alerting my variables? I'm attempting to pass a string stored in a variable from an external JavaScript file back to the main page using alerts. Initially, I suspected that the JavaScript was not fetching data cor ...

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

What is causing the search filter in the App.js code to malfunction?

After fetching a list of names from an array using the Fetch method, I attempted to implement a search filter by adding the resetData() method in my componentDidMount. Unfortunately, this resulted in an error as shown here: https://i.stack.imgur.com/1Z7kx. ...

NodeJS is facing a severe challenge in properly rendering HTML and its accompanying CSS code, causing a major

Once upon a time, I built a beautiful website while practicing HTML, CSS, and JS. It had multiple web pages and used Express for the backend. Unfortunately, I lost all the files associated with it and took a break from web programming for some time. Now, w ...

Connecting prop variables to component variables establishes a direct relationship between them

By assigning the props variable to a component variable, any changes made to the component variable will also reflect in the props... Parent Component: const prova = [ { 1: 'a' }, { 2: 'b' }, { ...