Unable to successfully transfer JSON data from JavaScript file to .NET controller using AJAX POST request

I'm facing an issue where I am trying to send a JSON string from the client (js) to the server (.NET controller) using AJAX post. However, when the data reaches the controller, the list is empty with a count of 0, which is puzzling me.

  • JS Code
btnAddMovie.addEventListener("click", () => {
    console.log(datesDict);

    var dataToSend = formatDataToSend();
    console.log(dataToSend);
    console.log(JSON.stringify(dataToSend));

    $.ajax({
        type: "POST",
        url: "SubmitMovieAdd",
        data: JSON.stringify(dataToSend),
        contentType: "application/json",
        success: function (response) {
            console.log(response);
        },
        error: function (request, status, error) {
            console.log(request.responseText);
        }
    });
});

function formatDataToSend() {
    var jsonToSend = [];

    for (const [key, value] of Object.entries(datesDict)) {
        jsonToSend.push({
            date: key,
            hours: value
        });
    }

    return jsonToSend;
}

In datesDict (dictionary), there are values like this: datesDict = 14/05/2024: ['15:00:00', '12:00:00']

In dataToSend, it looks like this: dataToSend = 0: {date: '14/05/2024', hours: Array(2)}

Final JSON.stringify output => [{"date":"14/05/2024","hours":["15:00:00", "12:00:00"]}]

  • Controller
[HttpPost("MyAdminDashBoard/MovieAdd/SubmitMovieAdd")]
public IActionResult SubmitMovieAdd(List<MovieAddJsonAppModel> json)
{
    return Content(json.Count().ToString());
}
  • Model
public class MovieAddJsonAppModel
{
    public string Date { get; set; }
    public List<string> Hours { get; set; }
}

Could someone please help me troubleshoot and resolve this issue? Thank you :)

Answer №1

It's important to double-check that the property names used in your C# model are an exact match with the keys in your JSON object. In this scenario, make sure you have properties named Date and Hours.

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

In Firefox, using the new Date function within a string does not function as expected

Why does the last log in the code snippet below not work in Firefox? (function() { String.prototype.toDate = function() { return new Date(this); }; console.log(Date.parse("2012-01-31")); console.log(new Date("2012-01-31")); c ...

What's the best method for concealing components: using a class to hide or removing them from the

I am encountering difficulties in React as I try to add a class to a component after a specific time duration. My goal is to apply the "hidden" class to a loading image, changing it to display: none after a few seconds. However, despite my efforts, I keep ...

Issues with AJAX not being triggered upon clicking as expected

I've been delving into AJAX for about 2 hours now, trying to understand how to make it work. It seems like the function is being called, as an alert works perfectly fine. When I tried a different method, it seemed to trigger the function automaticall ...

React-router can manage non-matching paths by utilizing a basic JavaScript router configuration

Is there a way to manage non-matching paths using plain JavaScript in React router configuration? const rootRoute = { component: 'div', childRoutes: [ { path: '/', component: App, childRoutes: [ requir ...

Unlock the Full Potential: Enabling Javascript's Superpowers through PHP Execution

I specialize in PHP and JavaScript. Currently, I am attempting to incorporate JavaScript functionalities into my PHP code. However, I am encountering an issue where the code is not functioning properly. The PHP code that executes the JavaScript code is as ...

What is the reason this switch statement functions only with one case?

Why is the switch statement not functioning properly? It seems to correctly identify the values and match them with the appropriate case, but it only works when there is a single case remaining. If there are multiple cases to choose from, nothing happens. ...

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

Is there a way to click on an ajax link?

AjaxOptions ajaxMainContent = new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "main_content" }; @Ajax.ActionLink("start new game", "Game", ajaxMainContent) I am looking for a way to trigger this action in javascript. function startNewGame(cost) ...

How can I employ CSS files within a Node module that is compatible with Next?

I recently made the switch from Gatsby to Next and I'm still learning the ropes. When working with Gatsby, I had a Node module that served as my UI library across different projects. This module utilized a CSS module file (style.module.css) that coul ...

Transforming a div into a clickable hyperlink

I have a JavaScript function that generates a div with a link inside it. Here is how the div and link are created: $('#info').find('#link').text("View"); //Creates a new link var eventLink1 = document.createElement('a& ...

Having trouble clicking or interacting with JavaScript using Selenium and Python

Issue: Unable to interact with elements on a specific webpage after opening a new tab. Using WebDriver Chrome. I can successfully navigate the initial webpage until I click a link that opens a new tab, at which point I am unable to perform any actions. ...

Avoiding HTML in JavaScript: Tips and Tricks

My application generates numerous elements dynamically based on server data in JSON format. This process involves embedding a significant amount of HTML directly within my JavaScript code, leading to pollution and making it increasingly challenging and l ...

Issue with submitting a form within a React modal - lack of triggering events

I am utilizing the npm package react-modal (https://www.npmjs.com/package/react-modal) in my project. The issue I am facing is that when I click on 'Submit', nothing happens. The function handleSubmit</a> is not being triggered, as no conso ...

Problem with submitting forms created dynamically using jQuery

I'm completely puzzled by this issue. I've been struggling to make it work, but for some reason, the submit event is not being captured in the first block where the login form is displayed: function appInit() { $.post(clubapp,function(d){ ...

The precision of the stopwatch is questionable

Just starting out with JS and jquery, I quickly put together a stopwatch code in JS that seems to work accurately up to 10 minutes. The issue arises after the 10-minute mark where it starts falling a few seconds behind (I compared it to a digital stopwatc ...

Loading HTML content in a WPF WebBrowser without encountering security messages

Currently, I am developing a WPF application in which I create the content of an HTML file as a string (including some JavaScript functions for calculations). After generating the string, I save it as an HTML file on my local disk and then reload it using ...

Why does the lazy loading feature keep moving the background image around?

While trying to incorporate lazy loading on my website, I encountered an issue where the image position would change after it was fully loaded and made visible. I experimented with rearranging the order in which my JavaScript and CSS files were called, bu ...

Incorporate a genre twist in animated films

Is there a way to implement an animated feature where the letters appear one by one in between a sentence, similar to what is seen on this page? On the linked page, there is a sentence displayed inside a banner that reads: Create meaningful documents Cr ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Load Angular modules dynamically

Is there a way to dynamically load a module (js, css and html) using a single directive at any point during the app's lifecycle? <my-module id="contacts"></my-module> The template for this directive looks like this <my-module id="con ...