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

How can I convert an integer to a string within a Laravel JSON object?

After upgrading my server to a more recent version of MySQL and PHP 7, I noticed a change in the way Laravel's response()->json() function handles tinyint data types. Previously, on PHP 5.5, it would always convert them into strings. However, with ...

Leveraging AJAX for database variable checks and PHP and JavaScript to redirect to specific pages based on the results

I am currently exploring the use of AJAX to validate variables in a database. The goal is to redirect to a specific page if the validation is successful. However, during this testing phase, I am not actually checking any variables. My focus is on verifying ...

What is the most effective way to alter the elements in a JavaScript array based on the total count of another element's value?

I have a task where I need to manipulate an array by adding or removing elements based on the total count of another value. let data = [ { "details": [ { "Name": "DataSet1", "Severity": "4& ...

What is the best approach to handle invalid parameters when deserializing an object from Json in C#?

I am attempting to deserialize an object that may have an invalid schema. In this scenario, I want all invalid parameters to be disregarded. My goal is to ensure that my application continues to function regardless of any unexpected changes in the JSON str ...

Create a CSS popup alert that appears when a button is clicked, rather than using

Is there a way to customize CSS so that the popup alert focuses on a button instead of just appearing like this? I have implemented this type of validation for a text box: <div class="form-group"> <label class="control-label col-sm-3" for="judul ...

Stop the web browser from storing the value of the input control in its cache

Many web browsers have a feature that saves the information you enter into certain fields so you don't have to type it again. While this can be convenient for most cases, I am faced with a situation where users must input a unique reference for a new ...

"The AJAX request triggers an internal 500 error whenever either a post or get request is

Whenever I attempt to submit a post or use the get method from my index.php file which calls Ajax_mysql.php through the Ajax function POST or GET, I encounter a frustrating Internal 500 error. The server doesn't provide any additional information abou ...

Creating enduring designs in Next.js

I've been diving into this amazing article and I'm puzzling over the implementation of persistence in Option 4. It seems like you would need to redefine the .getLayout method for each page. I'm uncertain about how nesting logic is handled fo ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

React app experiencing issues with Bootstrap offset functionality specifically when paired with a button element

I am struggling to position the button after two columns of space in this code snippet. Despite my efforts, the button remains pulled to the left and I can't seem to update it. { values.contact_persons_attributes.length < 2 && <div className= ...

Struggling to extract a value from a non-JSON string. Any tips on how to retrieve the desired data from this particular string format?

Example Here is a sample string a:1:{i:0;a:4:{s:8:"priority";i:0;s:6:"amount";s:2:"20";s:4:"type";s:5:"above";s:5:"total";s:1:"0";}}. How can one extract the value of s:2 from this non-JSON string? ...

The module 'AppModule' has unexpectedly declared a value of 'Component' that was not anticipated

Recently, I've been working on transitioning my application to the new angular2 webpack rc5 setup. I have successfully generated the app module using ng cli migration. However, I am facing an issue while trying to integrate a component from my own li ...

What is the process of transferring information from an AngularJS factory to a controller?

I am trying to access raw data object from an angularJS factory that serves as a dataSource for a kendo grid. Despite being able to console log the data in the factory, I'm facing difficulty populating the data object in the controller. How can I retr ...

Issues with Cordova and JQuery ajax functionality not operating as expected

I am facing an issue with implementing AJAX functionality in my Cordova app (CLI 6.3.1) on Visual Studio 2017. It works fine on the emulator, but I encounter a connection error when installing it on a mobile phone. I have already included CSP as shown bel ...

Troubleshooting issue with Json and Mysql

Here is my code for processing JSON data in PHP: include("connect.php"); $id = $_GET['lid']; function countRecords($fieldName,$tableName) { $sql = "SELECT * FROM `mail` WHERE confirmed = 'no' AND label_id = '". $id ."'"; $re ...

Oops! An issue occurred at ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 where a module cannot be located. The module in question is 'http'

I have been troubleshooting an issue with Next.js The error I am encountering => error - ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 Module not found: Can't resolve 'http' Import trace for req ...

"Utilizing Ajax technology for website functionality while implementing effective SEO strategies

I've been facing an issue with my website not being indexed by Google for the past 5 weeks. The problem is not just with internal pages, but with the entire website itself. When searching for "xyz," my website "ww.xyz.com" is completely ignored by Go ...

The perpetual cycle of redirection through middleware

Implementing straightforward middleware logic and encountering Encountered an infinite redirection in a navigation guard when transitioning from "/" to "/login". Halting to prevent a Stack Overflow. This issue will cause problems in p ...

Validation of JSON Failed

Encountered a 400 Bad Request error while attempting to POST an answer using Postman, it appears to be a validator issue. Despite multiple attempts, I have yet to resolve this issue. Below are details of the JSON data being sent in the POST request along w ...

Adding more dynamic parameters to the external script in index.html using Vue.js

I am looking to pass username and userEmail from the getters/user method in Vuejs, which is within index.html. Here is an example of how I would like it to be passed: <script>window.appSettings={app_id:"appId", contact_name: "Alexander ...