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:

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

The Upstash Redis scan operation

Attempting to utilize the @upstash/redis node client library for Node.js (available at https://www.npmjs.com/package/@upstash/redis), I am facing challenges in executing the scan command, which should be supported based on the documentation. Specifically, ...

Is there a way to make this eval() function function properly in Internet Explorer?

My JavaScript code is fetching another JavaScript "class" from a different XHTML page. The fetched JavaScript looks like this: (function() { this.init = function() { jQuery("#__BALLOONS__tabs").tabs(); }; }) Once the f ...

Implement the Vue.js @click directive in a location outside of an HTML element

I've set up a link like this: <a href="#" @click="modal=true">Open modal</a> Here's the data setup: export default { data () { return { modal: false } } } Is there a way to trigger the cli ...

Retrieving the chosen option from a dropdown menu without the need for a page

Currently, I am facing an issue with the view limit dropdown on my page that contains multiple filters for searching data from a Database. At the bottom of the page, there is a view limit dropdown separate from the main search form. This dropdown allows us ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

Verifying the presence of an ID within a jquery cookie

I encountered an issue with this code on a product page. Whenever I click the save button, it stores the product ID in a jQuery cookie. The IDs are stored in the cookie like this: 1,2,3,4... If an ID is already in the cookie, there seems to be a problem a ...

When querying a JSON array of objects in Greenplum PXF external table, an empty string is returned instead of the desired element

When accessing JSON data through an external table using the PXF JSON plugin in a multiline JSON table example, If we define the column as: "coordinates.values[0]" INTEGER, We can easily retrieve 8 from the JSON below: "coordinates":{ "type":"Poin ...

Customizing the Zoom Control Style in Vue Leaflet

I'm currently working on developing a Map App in Dark Mode using Vue, but I've encountered an issue with changing the style of the Zoom Control. Here's what I have tried so far: template> <div class="main-map"> <l ...

Keep duplicating a single object until it fills up the entire screen

Is there a way to make an HTML/CSS element repeat until it covers the entire screen height, without repeating it indefinitely? #container{ height: 100vh; width: 100vw; } .dotts{ background-color: yellow; border-radius: 50%; height: 20px; width: 20p ...

Unable to retrieve Celery task outcome in Django version 1.11

I am trying to retrieve Celery task results in Django using AJAX. Here is the view I have: def ajax_brand_count(request, task_id): extra_data = brand_count.AsyncResult(task_id) print("1", extra_data.state) print("2", extra_data.get()) if e ...

Converting JSON into Java objects

Received an unusual Json object from a third-party service provider and having trouble implementing it. Here is the JSON object: { "signers": [ "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e199989ba1808382cf828e8c"> ...

PHP scripting combined with AJAX technology can be used to effortlessly insert data

Hey everyone, I'm currently diving into the world of coding and facing an issue with an ajax/php script. My goal is to insert data into a database without having to refresh the page. Below is the code I've been working on: <?php require(&apo ...

Output the ID of each completed task from the JSON file using a bash script

Here is an example of a Json file: { "tasks": [ { "id": "nightly_1652299200", "repo": "tx/tx5", "branch": "dev", "type": "HealthCheck", ...

The server mistakenly sent the resource as a Stylesheet even though it was interpreted differently

Dear Fellow Coders, Could anyone lend a hand? I encountered this issue on my website after uploading it to my FTP: "Resource interpreted as Stylesheet but transferred with MIME type text/plain" </head> <body> <div class= "navbar navbar ...

The limitation of querying with String criteria in a MongoDB collection using Java

When attempting to query a collection in a database using a String field, no results are returned. However, querying with an Integer field yields results for the same dataset. The first attempted query, which uses a string value, does not return any resul ...

Syntax error triggered and caught by ajaxError

I have implemented a client-side ajax error handler using the following code: $(document).ajaxError(processAjaxError); $.getJSON('/data.json'); In the server side, I have defined a function as shown below: def get(self): self.response.he ...

Substitute the value in the object associated with a mystery key with a different value from the second object

I am dealing with the following objects: http ={" xxx": "#phone#","yyy": "1234", "zzz":5678 } input= {"phone": "2", "id": "258 }, Can someone help me find the #phone# val ...

Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success. I attempted the following code but couldn't get it to update. The ng-chan ...

Which is better: JavaScript, Json, or Html?

When working with an ASP.NET MVC view and using jQuery AJAX to update a div, the decision on whether to use a controller that returns a PartialView or JSON can depend on various factors. Consideration for both user experience and system performance is im ...

Developing a transparent "cutout" within a colored container using CSS in React Native (Layout design for a QR code scanner)

I'm currently utilizing react-native-camera for QR scanning, which is functioning properly. However, I want to implement a white screen with opacity above the camera, with a blank square in the middle to indicate where the user should scan the QR code ...