Sending an array of strings from an ajax call to an MVC controller

I'm encountering an issue where I have an array that I build up when a row is selected in my bootstrap data table. The problem arises when I try to pass this array from my view to the controller, which is supposed to fire up a partial view. Strangely, I am getting a null reference exception in my controller when I execute the code. Despite being able to see values for the array during debugging, it still shows as NULL. Any thoughts on why this might be happening?

AJAX:

function MoveSelected() {
    $.ajax({
        type: "Get",
        url: '@Url.Action("MoveSelectedRoute", "Transport")',
        data: { orders: completeArray },
        success: function (data) {
            $('#detail_MoveSelectedOrders').html(data);
            $('#modalMoveSelectedOrders').modal('show');
        }
    })
}

Controller:

public ActionResult MoveSelectedRoute(string[] orders)
{
    string OrdersToMove = string.Empty;
    foreach (string row in orders)
    {
        string orderNo = orders.ToString().PadLeft(10, '0');
        if (OrdersToMove == string.Empty)
        {
            OrdersToMove = orderNo;
        }
        else
            OrdersToMove = OrdersToMove + "," + orderNo;
    }
}

Answer №1

If you want to post back an array to the collection, make sure to include the traditional: true ajax option in your code.

$.ajax({
    type: "Get",
    url: '@Url.Action("MoveSelectedRoute", "Transport")',
    data: { orders: completeArray },
    traditional true,
    success: function (data) {
        ....
    }
})

Keep in mind that the traditional: true option is suitable for simple arrays only.

Another approach would be to stringify the data, specify the content type as application/json, and use a POST method instead of GET.

$.ajax({
    type: "Get",
    url: '@Url.Action("MoveSelectedRoute", "Transport")',
    data: JSON.stringify({ orders: completeArray }),
    contentType: "application/json; charset=utf-8"
    success: function (data) {
        ....
    }
})

An alternative solution is to send the values with collection indexers like this:

var data = {
    orders[0] = 'abc',
    orders[1] = 'xyz',
    orders[2] = '...'
}
$.ajax({
    type: "Get",
    url: '@Url.Action("MoveSelectedRoute", "Transport")',
    data: data,
    success: function (data) {
        ....
    }
})

Answer №2

To successfully convert your array, utilize

JSON.stringify({ orders: completeArray })
. Your C# code will then seamlessly map the array with its corresponding parameter.

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

Next.js throws an error when trying to access the document object while using React Aria overlays

Recently, I've been diving into Next.js for web development and stumbled upon commerce, a template specifically designed for e-commerce websites using Next.js. While exploring the codebase, I noticed the Sidebar component which leverages React Aria fo ...

Executing multiple setTimeout calls simultaneously can result in greater delays than anticipated

During my exploration of Node performance, I encountered an unexpected issue where an example involving 50 concurrent calls to setTimeout took over 4 seconds instead of the anticipated 500ms. The scenario involves a basic express server that waits for all ...

Webpack dynamically imports files from a folder

In order to streamline my development process, I have a specific structure for organizing React components. Each main component has its own components folder right alongside it. Currently, I find myself manually importing each component from the components ...

JavaScript error leading to ERR_ABORTED message showing up in the console

When I try to load my HTML page, my JavaScript code keeps throwing an error in the console. I am attempting to import some JavaScript code into VSCode using an app module for future reuse. The code is being run through a local server. Error Message: GET ...

Navigate your way with Google Maps integrated in Bootstrap tabs

Trying to display a Google Map in a vanilla Bootstrap tab has been quite the challenge. I created a fiddle based on the Bootstrap docs, and followed Google's instructions for the Gmap script. The map object appears initialized when checking console.di ...

Transforming a comprehensive php form into a single, streamlined page form

Hello everyone, I have a question that I need some help with. I currently have a multipage webform that functions well, except for the fact that each step requires the webpage to reload. Now, I am looking to transition it into a single-page form with steps ...

Best practices for displaying AJAX responses in MVC using CodeIgniter

When I have a form that submits to the submit_ajax method via AJAX, I want to return a JSON object upon receiving it as an AJAX request. In this scenario, there are two potential approaches. What would be the recommended way to achieve this while adhering ...

Is there a way for me to generate an array where I can easily access a particular 'card' whenever needed? (this question pertains to the content of the post)

I've been attempting to develop a card game in Python, but I've hit a roadblock when it comes to designing the card faces as callable objects. Below is my array of heart cards (I attempted to split the card suits into four different functions). H ...

Creating a circular shape with a radius that can be adjusted

I'm trying to create an expanding bubble-like circle of various colors when clicked on a blank page. The circle should continue increasing in size each time it is clicked, only stopping when the mouse click is released. I am looking to use HTML, CSS, ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

Jquery validation is ineffective when it fails to validate

I have implemented real-time jQuery validation for names. It functions correctly in real-time, however, when I attempt to submit the form, it still submits the value even after displaying an error message. Below is the code snippet for the validation: $ ...

What is the best way to create a full bleed background image that adjusts to different screen resolutions using CSS and JavaScript?

Similar Question: Full Screen Background Image in Firefox Check out: Is there a way to achieve a similar effect on a website where the content adjusts to different monitor resolutions? On the Ingress site, it seems like everything scales proportional ...

AngularJS: Substates not rendering properly

I'm encountering issues while trying to incorporate nested states in my project. Although the View template and JavaScript calls are being made and loaded, the screen is not changing - in other words, the nested screen is not displaying. http://{dom ...

What are the reasons behind the min and max range method not providing accurate results?

I am in need of a method that can verify if a given value falls within the valid range of -064.000000 to -180.000000 and 142.000000 to 180.000000. The structure of my ranges object is as follows: "ranges": { "range1": { "min& ...

What causes images to be omitted from a PDF file when using mywindow.print()?

Here is the scenario I am dealing with: On a particular webpage, there is a print button. The page contains various information, including receipts. When the user clicks on "print", I want only the receipts to be printed: Below you can find the code for ...

What is the best way to organize objects based on their timestamps?

I am faced with the task of merging two arrays of objects into a single array based on their timestamps. One array contains exact second timestamps, while the other consists of hourly ranges. My goal is to incorporate the 'humidity' values from t ...

Refreshing certain sections of a webpage without the need to refresh the entire page

If you want to understand better, it would be helpful if you could check out my website first at: The main part of the website is a stream from Own3D.tv displayed through an iframe (line 342). My objective is to have the ability to click on a specific str ...

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

Error encountered while attempting to revert from .NET 4.5 to .NET 4.0

Recently, I encountered an issue with my WPF application that relies on .NET framework 4.5. This application utilizes MahApps.Metro and other libraries such as System.Data.SQLite. However, when I attempted to downgrade the .NET framework version to 4.0, ...