Sending an Array from JavaScript to Asp.net Core

Below is the javascript code that invokes the asp.net CustomHeatMapDate function

$('.Date').change(function () {
    var data = [];
    console.log();
    var dateList = [{"Date":"03/23/2016"}, {"Date":"03/24/2016"}];
    $.ajax({
        async: true,
        type: "GET",
       url: "/Home/CustomHeatMapDate",
       data: { Date: dateList },
        dataType: "json",
        success: function (data) {
            console.log(data);
            for (var i = 0, len = data.length; i < len; i++) {
                pushdata(data[i]);
            }
        }
    })

Here is the Asp.net Controller

public IActionResult CustomHeatMapDate(Array[] Date)
{           
    return View();
}

However, there is an issue with the Date Array being null

Answer №1

Upon reviewing the code, there are a few key issues that need to be addressed along with solutions on how to fix them.

The first issue lies in the structure of the data being sent to the controller. Currently, it is formatted as

{Date:[{"Date":"03/23/2016"}, {"Date":"03/24/2016"}]}
, but it should actually be structured like
{Date:["03/23/2016", "03/24/2016"]}
. By making this adjustment, you will ensure that a flat array is sent instead of an array of objects.

The second problem pertains to the datatype specified in the controller, which is currently set to Array[] expecting an array of arrays. It should be changed to DateTime[] to anticipate an array of date(times). Additionally, dates should be modified to follow the format 2016-03-23 for proper deserialization.

Lastly, using a GET method may pose limitations when passing structured data in parameters due to query string restrictions. Consider utilizing a POST request instead to avoid potential length constraints. Alternatively, add traditional:true to the ajax properties if sticking with a GET approach, as suggested by Alexandru-Ionut Mihai.

TL;DR Rectify data structure discrepancies on client and server sides.

In conclusion, here is an updated version of your code:

JS

$('.Date').change(function () {
    console.log();
    var dateList = ["2016-03-23", "2016-03-24"];
    $.ajax({
        type: "POST",
        url: "/Home/CustomHeatMapDate",
        data: {
            Date: dateList
        },
        dataType: "json",
        success: function (data) {
            console.log(data);
            for (var i = 0, len = data.length; i < len; i++) {
                pushdata(data[i]);
            }
        }
    })
});

C#

public ActionResult CustomHeatMapDate(DateTime[] Date)
{
    return Ok();
}

P.S There is no need to explicitly set async:true as JQuery Ajax defaults to true for asynchronous requests.

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

Unable to change data in table TD using AJAX and PHP received JSON array

I am currently facing an issue with a PHP-AJAX script that is responsible for deleting financial rows from a table. The PHP script is functioning correctly and successfully deleting the rows. However, the problem arises within the success function of the A ...

The data type 'string' cannot be assigned to the type '(url: string) => string'.ts(2322)

I am working with a Material UI copyright component: export default function Copyright(link: string, text: string) { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link co ...

Using a carousel component in Bootstrap

Just starting out with this, trying to customize Bootstrap to change slides automatically. I followed the documentation at https://getbootstrap.com/docs/4.3/components/carousel/ but for some reason, the slides aren't changing on an interval, even thou ...

Leveraging JavaScript within PHP script

I am currently developing a booking system that involves creating events in a table using PHP. I want to implement a script that will run when a user tries to book an event and then submits the form to PHP. This script will help me determine if the user ha ...

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

How can you pick the element that is nearest to the top of a window?

My goal is to have a fixed list of page sections on the side that highlights the link of the section you're currently viewing as you scroll through the page. This is the code I've come up with: $(document).scroll(function(){ $allSections = $(&a ...

What is the best way to prevent double clicks when using an external onClick function and an internal Link simultaneously

Encountering an issue with nextjs 13, let me explain the situation: Within a card component, there is an external div containing an internal link to navigate to a single product page. Using onClick on the external div enables it to gain focus (necessary f ...

Pusher authentication issue: socket ID not defined

I am currently facing an issue while trying to establish a private channel for users to transmit data to my node.js server. Upon making the request, I encounter an error where pusher:subscription_error is returned with the error code 500. Upon checking my ...

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

Guide on adding a post type via the command line: Issue encountered - Anticipated POST console HTML error

Facing Error: EXPECTED POST in JQuery Ajax Call Encountering the same issue as mentioned in the provided link. The need is to switch from GET to POST, but direct alteration of ajax code is not feasible. It must be done dynamically using JavaScript through ...

The MUI makeStyles() class has been implemented, yet the styles are not being displayed when using classList.add('class-name')

Currently, I am utilizing MUI makeStyles() to create a series of CSS classes. Within these classes, I am dynamically including and excluding one specific class to my Box element during file drag-and-drop events. The class is successfully added, as I can o ...

Troubleshooting issue with Onchange in select HTML element within Django

I'm working with a Problems model in my project. In my Models file models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA ...

Is there a way to prevent the background color from filling the entire container?

In the visual representation provided below, there is a header element consisting of a back arrow and a name. The arrow container has been assigned flex: 1, while the arrow and name containers have been set to flex-start and flex-end respectively. This co ...

Is it possible to load HTML content within a Sweet Alert pop-up

Below is the code I am using to call Swal: window.swal({ title: "Checking...", text: "Please wait", imageUrl: "{{ asset('media/photos/loaderspin.gif') }}", showConfirmButton: false, allowOutsideClick: false }); $.ajax({ t ...

The combination of Spring Boot and Angular's routeProvider is a powerful

I have been working on a project using Spring Boot, REST, and AngularJS. While I successfully implemented the back end with REST, this is my first time using AngularJS. Despite watching numerous tutorials and following them step by step, I am still facing ...

Utilize a solo input field to upload either a video or image, and showcase a preview of the uploaded content in a

I'm currently working on creating an input field that allows for the upload of both images and videos. Although I am able to successfully upload the files, I'm encountering an error when trying to display a preview. The code snippet below outline ...

Organizing subcategories within a dropdown checklist

I am currently working on a list that utilizes dropdownchecklist and I am looking to create subgroups from the elements in the list. The goal is that by clicking on a subgroup checkbox, it will automatically check all elements associated with it. Below is ...

Optimizing CSS With jQuery During Browser Resize

I am currently facing an issue with recalculating the height of the li element during window resizing or scrolling. Strangely, on page load, the height is no longer being re-calculated and set to the ul's child height. Here is the code I have written ...

Sort through the array using a separate array in Vuejs

I am currently working with two arrays: { "products": [ { "name": "Jivi", "Hint": "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche", "frequency": ["1", "2", "8"] }, { "name": "Adynovi", ...