Issue with ASP.NET Core Controller not properly receiving complete JavaScript array object from Ajax call

When passing a JavaScript Object Array through ajax to the controller, I noticed that if there are more than 11 objects in the array, the controller receives it as null. However, with 11 or fewer objects, the array is received successfully. Here is an example: https://i.sstatic.net/amqxP.png

Upon receiving the passed employee array in the controller, it looks like this: https://i.sstatic.net/8p0Kh.png

But when I pass a larger JavaScript array object, its value ends up being null. https://i.sstatic.net/pHFqj.png

https://i.sstatic.net/OWCTF.png

I've tested this issue with an array of 50 objects - all of which match the Model properties perfectly and have confirmed there's nothing wrong with the modal.

If anyone can point out where I might be going wrong, please let me know.

Below is a snippet of my JS code: Essentially, I'm attempting to read data from a CSV file and store it in a JavaScript array. The properties of the JavaScript array align with those of the model fields.

let employees = [];
let reader = new FileReader();

$("#btnSave").click(function () {
    Save();
})

$("#file").change(function (e) {
    //getting the uploaded file
    let fileUpload = $("#file").get(0)
    let file = fileUpload.files[0];
    //load the reader
    reader.onloadend = function (evt) {
        let lines = evt.target.result;
        if (lines && lines.length > 0) {
            let allRows = CSVToArray(lines);
            let header = allRows[0];
            let thead = $('thead tr')
            thead.html("")
            let tbody = $('tbody')
            header.forEach(h => thead.append(`<th>${h}</th>`))
            for (let i = 1; i < allRows.length; i++) {
                tbody.append('<tr>')
                let cellArr = allRows[i];
                let emp = {}
                for (let k = 0; k < cellArr.length; k++) {
                    emp[allRows[0][k]] = cellArr[k] + "";
                    tbody.append(`<td>${cellArr[k]}</td>`)
                }
                tbody.append('</tr>')
                employees.push(emp)
            }
        }
    }
    reader.readAsBinaryString(file)
})

function CSVToArray(strData, strDelimiter) {
    strDelimiter = (strDelimiter || ",");
    let objPattern = new RegExp(
        (
            "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
            "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
            "([^\"\\" + strDelimiter + "\\r\\n]*))"
        ),
        "gi"
    );
    let arrData = [[]];
    let arrMatches = null;

    while (arrMatches = objPattern.exec(strData)) {
        let strMatchedDelimiter = arrMatches[1];
        let strMatchedValue = [];
        if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
            arrData.push([]);
        }
        if (arrMatches[2]) {
            strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"");
        } else {
            strMatchedValue = arrMatches[3];
        }
        arrData[arrData.length - 1].push(strMatchedValue);
    }
    return (arrData);
}

function Save() {
    console.log( employees)
    if (employees.length > 0) {
        $.ajax({
            url: '/Master/SaveMaster',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify(employees),
            success: function (result) {
                /*for (let k = 0; k < result.length; k++) {
                    $('tbody tr:eq(' + (result[k].employeeId - 1) + ')').css('border', '3px solid #dc3545');
                    let props = Object.entries(employees[result[k].employeeId])
                    console.log(result[k])
                    let cellIndex = props.findIndex(p => p[0] === result[k].field)
                    $('tbody tr:eq(' + (result[k].employeeId - 1) + ') td:eq(' + cellIndex + ')').css({ 'background-color': '#dc3545', 'color': '#ffffff' });
                    $('tbody tr:eq(' + (result[k].employeeId - 1) + ') td:eq(' + cellIndex + ')').attr("title", result[k].error)
                }
                $(".main-container").append(`
                       <div class="alert alert-success alert-dismissible fade show" role="alert">
                           Data Successfully imported into the database
                       </div>
                    `)*/
            },
            error: function (result) {
                console.log(result)
            }
        })
    }
    else {
        alert("No Data Found.");
    }
}

Here is my controller:

        [Route("/Master/SaveMaster")]
        [HttpPost]
        public List<MasterError> SaveMaster(List<MasterData> masterData)
        {
            List<MasterError> masterErrorsList = new List<MasterError>();

            //for(int i = 0; i < masterData.Count(); i++)
            //{
                //Employee employee = new Employee();
                //employee.ArabicName = masterData[i].ArabicName;
                //employee.Code = masterData[i].Code;
                //employee.Email = masterData[i].Email;
                //employee.FirstName = masterData[i].FirstName;
                //employee.LastName = masterData[i].LastName;
                //employee.MiddleName = masterData[i].MiddleName;
                //employee.Mobile = masterData[i].Mobile;
                //employee.PassportName = masterData[i].PassportName;
                //employee.PassportNo = masterData[i].PassportNo;
                //employee.ResidentId = masterData[i].QatarID;
                //checkModel(employee);
            //}
            return masterErrorsList;
        }

Answer №1

Unfortunately, the solution provided above didn't solve my issue (possibly due to the larger size of my array), but I found success with the following approach.

[Route("/Master/SaveMaster")]
[HttpPost]
[RequestFormLimits(ValueCountLimit = int.MaxValue)]
public List<MasterError> SaveMaster([FromForm] List<MasterData> masterData)

Implementing this code was all it took for everything to work seamlessly!

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

Error code 500 was encountered while processing the JSON response

Whenever I attempt to make an ajax POST Call that returns JSON, I encounter an Internal Error. The ajax call originates from a JS page: $.post( 'FilterAsJson', $(formWithReportData).serialize(), function(data){funtion_body} ); This i ...

Executing a JavaScript function within a PHP echo statement

I am completely new to working with AJAX and PHP echo variables or arrays. However, I have managed to successfully display images on my website by passing variables from AJAX to PHP and back. The only problem I am encountering is when I try to call a Javas ...

What could be causing my YouTube code to malfunction with certain playlists?

Check out the first jsfiddle playlist here The Alum Songs Playlist is working perfectly, but unfortunately, the same code is not functioning for another playlist ID. View the second jsfiddle playlist here The Medical Animated Playlist is currently not w ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

The retrieval of JSON file using $.GetJson() is unsuccessful from local directory

There is a basic autocomplete program in place. The data entered in the textbox is successfully captured while debugging, however, the GetJson() function fails to retrieve the JSON file, causing the program to malfunction. Here's the relevant code sn ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

What could be causing the data-title attribute to not update in AngularJS?

When utilizing AngularJS and Bootstrap's popover, I have successfully bound to data-content, but am encountering issues with binding to data-title: <li data-trigger="hover" data-placement="bottom" data-title="{{'Memory limit' | l10n}}" d ...

Loop through the data string in Ajax using a For Loop to populate it

I am currently working on a loop that inserts select tags based on the number of rows. Each select tag will have an ID like selID0, selID1, selID2, and so on. My goal is to call an AJAX function to determine which tag is not selected when the submit button ...

Using jQuery to fetch and read the source code of a specified URL

I'm facing an issue with extracting the source code of a website URL into a variable. Here is my current approach: <script type="text/javascript"> debugger; $(documnet).ready(function () { var timer = $.ajax({ type: ...

JavaScript on the client side or the server side?

I am faced with a challenge on my report page where I need to filter customers based on specific criteria and highlight certain details if their registration date falls after a specified date, such as 1st January 2011. With around 800 records to showcase, ...

Getting JSON or JSONP data through a XAMPP local server is a straightforward process

After setting up a local server with XAMPP, my goal is to retrieve JSON / JSONP data from that server. Additional query: Do I need to upload the JSON file directly onto the server? Or can I achieve this using somePHPcoding? If so, which? I have come ac ...

Error: The javascript function is unable to execute because undefined is not recognized as a function

I've been struggling with an error in my "bubble sort" function that I wrote to organize a list of images. Whenever I run the function, I keep getting the message "Uncaught TypeError: undefined is not a function". Can anyone provide some guidance? $j ...

Executing a function in Node-Express with a database connection at the beginning of the application

I am relatively new to Node.js and currently working on a Node.js - Express solution as a back-end for an AngularJS web application. My goal is to send an email when the MSSQL database query returns specific information. I have successfully implemented thi ...

Unable to display label in form for Angular 2/4 FormControl within a FormGroup

I'm having trouble understanding how to: Use console.log to display a specific value Show a value in a label on an HTML page Display a value in an input text field Below is my TypeScript component with a new FormGroup and FormControls. this.tracke ...

What is the best way to locate an element through its parent?

I am working with the following HTML structure: <div class="row" id="row-1"> <div class="row-wrapper"> <div class="cell-1"></div> <div class="cell-2"></div> <div class="cell-3"></div> ...

Troubleshooting Django Python: Why can't I retrieve a JS object sent via AJAX in my Python QueryDict?

As I work on my Django project, I've set up a system for data exchange between the server and client using javascript and python with AJAX. To make things easier, I created a config object in JS to store important parameters that both the server and J ...

What is the best method to incorporate a JavaScript object key's value into CSS styling?

I am currently working on a project in React where I'm iterating over an array of objects and displaying each object in its own card on the screen. Each object in the array has a unique hex color property, and my goal is to dynamically set the font co ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Variation in the buffer size of embedded delegates

While working with an inline function, I encountered a scenario that sparked several questions in my mind. Example 1: (global testDeligate) [Serializable] class TestClass { Func<int, int> testDeligate = (a) => { a = +10; a = +20; return a ...

Numbering each numeral

Looking to add a sequence number next to each digit using jQuery or JavaScript: If I enter the following numbers: 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9, 10 and so on then the desired output should be: 1.1, 1.2, 1.3, 2.1, 3.1, 4.1, 5.1, 5.2, 5.3, 6.1 ...