Transmission of JSON to a C# controller via AJAX results in a Count value of zero in .NET 7

Whenever I attempt to send a JSON object to my controller, the parameter isn't being received.

This is the JavaScript code snippet:

var input = document.getElementById("input");

input.addEventListener('change', function () {
    const reader = new FileReader();
    reader.readAsText(input.files[0]);
    reader.onload = () => {
        const text = reader.result;
        var result = text.replace(/([0-9":])/g, '');
        result = result.split(/\r?\n/);
        console.log(result);

        var arr = new Array();

        result.map(function (element) {
            var cat = {
                'Name': element.replace(/[\u200B-\u200D\uFEFF]/g, '')
            };

            arr.push(cat);
        })

        jsonObject = JSON.stringify(arr);

        console.log(jsonObject);

        $.ajax({
            url: 'Categoria/BulkPost',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'JSON',
            data: jsonObject,
            traditional: true,
            success: function () {
                alert('Success!');
            }
        });
    }
});

This is the relevant part of my controller:

[HttpPost]
public JsonResult BulkPost(List<Categoria> categorias)
{
    //Perform some magic here
}

The model used in this process:

[DataContract]
public class Categoria
{
    [Key]
    public int IdClas { get; set; }
    [Required]
    [DataMember(Name = "Name")]
    [DisplayName("Category Name")]
    public string Name { get; set; }
}

And here is the generated JSON structure:

[
   {
      "Name":"Functional Aids"
   },
   {
      "Name":"MEDICAL EQUIPMENT AND HOSPITAL SUPPLIES"
   },
   {
      "Name":"Inventory"
   },
   ...
]

I've attempted various solutions found in similar queries but none have worked for me :(. Hopefully, someone can assist me with this issue.

Answer №1

Whenever I attempt to send a JSON to my controller, I am not receiving any parameters.

Actually, the advice given by @Serge is accurate. By default, ajax requests are of type

application/x-www-form-urlencoded
, but since you are sending JSON data, simply using the List<Categoria> categorias signature in your method will not be able to communicate properly with your controller method that handles ajax JSON data requests.

It is crucial to decorate the request body sent via ajax with the [FromBody] attribute. This ensures that the parameter in your controller action can correctly receive and process the list specified in the [FromBody] attribute, preventing mismatch issues with the method signature.

Correct Controller Action Signature:

    [HttpPost]
    public JsonResult BulkPost([FromBody] List<Categoria> categorias)
    {
        //....rest of code 
    }

Output:

I have made the necessary adjustment with the correct [FromBody] attribute and it is now functioning as expected, as demonstrated below:

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

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

https://i.sstatic.net/7mpVV.gif

Note: For further details, please refer to this official documentation.

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 occurred when invoking jQuery.ajax in C# .NET is not recognized as valid

Take a look at my JQuery script below: $("#click_me").click(function() { jQuery.ajax({ type: "POST", url: "http://localhost:8882/Greet.aspx", data: '', ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

The debate between ensuring input validity and making fields mandatory on multi-page forms

I am currently working on a multi-page form and using jQuery Validate to validate it. The user has four options: next, prev, save, submit. Save, next, and prev all save the current page within the form; whereas submit is similar to save, but triggers addi ...

Is using JQuery recommended for implementing onclick and onchange events?

Hello there, I'm completely new to the world of jQuery and currently facing a bit of confusion. Here's my dilemma: should I be utilizing jQuery with the onclick event or the onchange event for an element using something like this: $(selector).som ...

Wordpress tabs with dynamic content

I came across a code on webdeveloper.com by Mitya that had loading content tabs and needed the page to refresh after clicking the tab button. It worked perfectly fine outside of WordPress, but when I tried implementing it into my custom theme file, it didn ...

Error message "Connection refused because of timeout duration exceeded"

File "/home/abhigenie92/stanford2/Code/dependencies.py", line 18, encountering error in the get_dependencies function: result = loads(server.parse(sentence)); File "/home/abhigenie92/stanford-corenlp-python/jsonrpc.py", line 934, while making a call ...

The data being transmitted by the server is not being received accurately

Hey there! I've recently started using express.js and nodejs, but I've encountered an issue where my server is sending me markup without the CSS and JS files included. const express = require('express'); const app = express(); const htt ...

Encountering error while trying to set up Hardhat using npm - "npm ERROR! Invalid URL code"

PS C:\Users\jawad\OneDrive\Desktop\NFT Project> npm install --save-dev hardhat npm ERR! code ERR_INVALID_URL npm ERR! Invalid URL npm ERR! A complete log of this run can be found in: C:\Users\jawad\AppData\L ...

Exploring the inner workings of self-referencing mechanics in functions

In a recent coding scenario, I encountered this situation: I attempted to define the func1() function and add several static methods to it simultaneously by passing it through the _init() function along with a hash containing properties to attach. However, ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...

Transform your scene into a stunning 3D texture using THREE.js's 3D Render Targets feature

After exploring the THREE.js example available here, I am curious about how to avoid scenes rendered as textures from appearing 'flattened'. Essentially, I want to maintain the depth illusion within the scene when using a WebGLRenderTarget. I ha ...

Refusing to cease downloading music on the local server through the embedded audio element

I was trying to setup background music on my website, but when I test it localhost, the music download instead of playing. However, when I tested with the full path, it played as expected. How can I prevent the download from happening in localhost? Here i ...

Enrich the returned result set by including additional data in Mongoose

Within a MEAN environment, utilizing mongoose, I am attempting to include additional data in the returned query result. The purpose is to add a 'thumbnail' field (which represents the calculated path of the thumbnail image) to each author in the ...

Is there a way to refresh my list following a POST request when utilizing a separate endpoint?

I'm struggling with updating my list after a POST request. I haven't been able to find any solutions online. Typically, I would just push an object into an array, but it seems different in this case. This function utilizes 2 API endpoints. The f ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

Does the built-in waiting mechanism in Protractor automatically handle promises?

While browsing through Stack Overflow, I stumbled upon this response in a discussion about Protractor tests and asynchronous solutions: 'AFAIK expect waits internally for the related promises.' I have tried looking through the official Protract ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

Experiment with parsing multiple outputs instead of repeatedly coding them as constants in Node.js

In my application, I am parsing multiple database data using cron and currently, I have it set up to create a const run for each data to find the dag_id and manually test the determineCron function one at a time. How can I create an array so that the "dete ...

Does AngularJS have a feature similar to jQuery.active?

As I utilize selenium to conduct tests on my application, I am encountering numerous ajax calls that utilize $resource or $http. It would be convenient if there was a method in angular to monitor active ajax requests so that selenium could wait until they ...