Is there a way to use JSON.stringify() to post multiple arrays at once?

Trying to send multiple arrays to the controller using Ajax post. Initially, there is a model structured like this:

public class EnrollmentOptionsVM
{
    public virtual string OptionID{ set;get;}
    public virtual string UserChoice { set;get;}
    public virtual string TchOptionID { set; get; }
    public virtual string TeacherChoice { set; get; }
}

Subsequently, the script used for the process:

<script type="text/javascript">
    var $checkboxes = $('input[type="checkbox"]');
    var $strInstructors = $('input[name="instructorString"]');
    $(document).ready(function () {
        $('#saveBtn').click(function () {

            var teacherOptions = [];
            var options = [];
            $.each($checkboxes, function () {
                if ($(this).is(':checked')) {
                    var item = { "UserChoice": "checked", "OptionID": "YouCanSetIDHere" };
                } else {
                    var item = { "UserChoice": "unchecked", "OptionID": "YouCanSetIDHere" };
                }
                options.push(item);
            })
            $.each($strInstructors, function () {
                if ($(this).is(':selected')) {
                    var tchItem = { "TeacherChoice": "checked", "TchOptionID": "SetTchIDHere" };
                } else {
                    var tchItem = { "TeacherChoice": "unchecked", "TchOptionID": "SetTchIDHere" };
                }
                options.push(tchItem);
            })
            $.ajax({ 
                type: 'POST', 
                url: '@Url.Action("EnrollmentRefresh", "Student")',
                contentType: 'application/json',
                data: JSON.stringify({firstArray:options, secondArray:teacherOptions})
            }).done(function (html) {

            });

        });
    });
    </script>

The action signature in the controller:

[HttpPost]
    public ActionResult EnrollmentRefresh(List<EnrollmentOptionsVM> checkedOptions)
    {}
    

When attempting to send multiple arrays using JSON.stringify(), it only works with sending one array. How can I achieve sending multiple arrays?

UPDATE 1

<script type="text/javascript">
    // Same script as before...
    </script>

Changes made in the controller:

[HttpPost]
    public ActionResult EnrollmentRefresh( List<EnrollmentOptionsVM> checkedOptions, List<TeacherOptionMV> selectedTeachers)
    {}
    

The two ViewModels used are:

public class TeacherOptionMV
{
    public virtual string TchOptionID { set; get; }
    public virtual string TeacherChoice { set; get; }
}

And

public class EnrollmentOptionsVM
{
    public virtual string OptionID{ set;get;}
    public virtual string UserChoice { set;get;}
}

Answer №1

Instead of sending multiple arrays labeled as

{firstArray:options, secondArray:teacherOptions}
, it is recommended to send a single object containing two properties: firstArray and secondArray. Ensure that your controller is set up to receive just one array of EnrollmentOptionsVM. To optimize this process, consider updating the EnrollmentRefresh method to accept an object with fields such as firstArray and secondArray as arguments.

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

Transferring the values of JavaScript objects to HTML as strings

My goal is to generate HTML elements based on the values of specific JavaScript objects that are not global variables. However, when attempting to execute the code below, I encounter an error stating "params is not defined." What I actually aim to achieve ...

The error message for ExpressJS states: "Headers cannot be set after they have already been sent."

Currently, I'm facing a challenge with ExpressJS and am having trouble finding the necessary documentation to resolve it. Technology Stack: body-parser: 1.17.0 express 4.15.0 multer: 1.3.0 MongoDB Postman The current view consists of 3 fields: n ...

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...

Leveraging the useEffect hook to make multiple API calls in ReactJS

I have a useEffect function in my react component where I am calling the API videoGridState. The issue I am facing is that the API is being called twice; once when the page initially reloads and again when the count changes. I want it to be called only onc ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

"Enhance Your Website with qTip2 Feature to Load Multiple AJAX Sites Simult

I'm currently utilizing the qTip2 library for my project and I've implemented their AJAX retrieval functions following this example: http://jsfiddle.net/L6yq3/1861/. To enhance my query, I have modified their HTML to include multiple links. The ...

Exploring the potential of Bootstrap/bootflat and jQuery progress bars

I am attempting to display and animate a progress bar while loading an HTML page into a div using jQuery. The progress bar I am using is from Bootstrap (Bootflat) and has the following structure: <div class="progress" style="visibility:hidden;"> ...

Creating a text design that spans two lines using Scalable Vector Graphics (SVG

I am working with an SVG that displays strings pulled from an Array... {"label":"Here is an example of the string...", "value":4}, The text above is shown in an SVG element as... <text>Here is an example of the string...<text> I would like ...

What steps can I take to address the problem of my undefined .length value?

I encountered a length error while executing line 2 in this code snippet. index.js:10 Uncaught TypeError: Cannot read property 'length' of undefined" Sample Code: <div class="formCustomerName"> <label>Name:</label> ...

What is the correct way to store user input in the "store" using vuex.js? Can you help me identify where I went wrong?

On the third day of my suffering, I seek your help. Can you please guide me on how to save text input in "store" in vuex.js and then add it to the value of the same input itself? I've attempted it like this but seem to be making a mistake somewhere. ...

Having trouble getting the onClick event to trigger in React?

I have a button in my navbar that triggers a submenu (list of items) to display when clicked. Each item is a separate child component and I want them to trigger an event when clicked. However, the onClick event listener does not seem to be working. Other m ...

Record every action taken in the browser and compile it into a detailed HTML report

I am looking for a way to record and display all the browser actions performed in a test script in an HTML report. I am using protractor along with protractor-html-screenshot-reporter for reporting purposes. Is there any tool or API available that can he ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

Mastering the art of iterating through a JSON response

Looking to populate a combobox with data from the database. Upon accessing mystream.php?theLocation=NewYork, I receive the following JSON response: RESULT {"result": [{"theID":"36"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork ...

Struggling with defining the default value for a JavaScript array

One interesting feature on my website is a changing h1 heading that updates when the user clicks a button. However, I encountered an issue where, upon initial page load, the h1 appears empty and only populates with text after the button is clicked. I am ...

My mocks for Jest's readFile and writeFile functions are not being loaded

Just wondering, when using jest.mock(), can I only mock the entire module or can I also mock exported functions and constants? In my app.js file, I am using const fileSystem = require('fs'). I am trying to test an method in the app that reads a f ...

Is there a way to prevent the context menu from appearing when tapping on an image on a mobile phone?

When attempting to move an image on the screen with a touch event, a popup appears in Chrome when pressing and holding the image. This popup usually includes options to save the image. Is there a way to disable this popup so I can freely move the image w ...

Adding the AJAX response to an array within the AngularJS framework

I am currently working on a function that involves array objects. $http({ method: 'GET', url: 'select.php' }).then(function success(response) { alert(response); //$scope.posts=response.data; ...

Ways to retrieve the initial key object received through an AJAX request

I have a form with three dynamic dropdowns. The second dropdown depends on the first one, and the third dropdown depends on the second one. Therefore, selecting an option in the first dropdown will automatically populate the next two dropdowns. Below is t ...