Receiving a JavaScript Ajax Post List in a C# Method

Can someone guide me on how to pass a list of valid Targets into the method PassThings() from Javascript to C#? Specifically, I need help with sending data like the example below using a Javascript $.ajax post.

{
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 1,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 2,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 3,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "LopTargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 2,
    "InventoryElementID": 1,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  } 

I have been struggling to send any kind of list from my Javascript $.ajax post to the C# method PassThings().

So far, I have only managed to hard code the variable OneOfNine, which represents a single valid Target in JSON format.

This was done to test if the syntax sent by Javascript is correct and if my

JsonConvert.DeserializeObject<Target>(OneOfNine)
would work as expected.

public class Target{       
    public virtual string OverheadID { get; set; }//not a true Fkey
    public int ValuationClassID { get; set; }//not a true Fkey     
    public int InventoryElementID { get; set; }//not a true Fkey
    public decimal? Target_A_LC { get; set; }//LOP Target A Local Currency
    public decimal? Target_A_QTY { get; set; }//LOP Target A Qty
    public decimal? Target_B_LC { get; set; }//Target B Local Currency
    public decimal? Target_B_QTY { get; set; }//LOP Target B Qty
    public string TargetDescription { get; set; }//optional text reference 
}   

public IActionResult PassThings()
{ 

    var OneOfNine = "{ \"OverheadID\": \"ASASAS\", \"ValuationClassID\": 2, \"InventoryElementID\": 3, \"Target_A_LC\": 0, \"Target_A_QTY\": 0, \"Target_B_LC\": 0, \"Target_B_QTY\": 0, \"TargetDescription\": \"na\" }";
    var deserial = JsonConvert.DeserializeObject<Target>(OneOfNine);

    var resource =
    new Target
    {
        OverheadID = deserial.OverheadID,
        ValuationClassID = deserial.ValuationClassID,
        InventoryElementID = deserial.InventoryElementID,
        Target_A_LC = deserial.Target_A_LC,
        Target_A_QTY = deserial.Target_A_QTY,
        Target_B_LC = deserial.Target_B_LC,
        Target_B_QTY = deserial.Target_B_QTY,
        TargetDescription = deserial.TargetDescription
    };

    return Ok(resource);
} 

I attempted setting it up like this

public IActionResult PassThings([FromBody]List<Target> things)

And here's the corresponding Javascript code.

$.ajax({
    type: 'POST',
    //contentType: 'application/json; charset=utf-8',
    accepts: 'application/json', //mandatory activity
    contentType: 'application/json', //mandatory activity
    url: '/api/APILopTargets/PassThings',
    data: JSON.stringify(things)
}); 

Answer №1

If you want the URL to be /api/APILopTargets/PassThings, make sure to configure the ApiController as shown below:

[Route("api/[controller]")]
[ApiController]
public class APILopTargetsController : ControllerBase
{
    [HttpPost("PassThings")]//add the attribute
    public IActionResult PassThings([FromBody]List<Target> things)
    {...}
}

JavaScript:

var things = [
      {
       "OverheadID": "31l",
       "ValuationClassID": 1,
       "InventoryElementID": 1,
       "Target_A_LC": 0,
       "Target_A_QTY": 0,
       "Target_B_LC": null,
       "Target_B_QTY": null,
       "TargetDescription": null
      },
      {...},
      ...
    ];

$.ajax({
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        url: '/api/APILopTargets/PassThings',
        data: JSON.stringify(things),
        success: function (result) {

        }
 });

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

What is the best way to display all checked checkboxes even when the page is reloaded?

I am facing an issue with my website - it is using JavaScript to search for checked checkboxes. $(function () { var $allELements = $('.input-box'); var $selectedElementsListing = $('#selectedElements'); var $selec ...

Issue with Route Transition in React Router version 4 when using Styled Components

I am currently in the process of constructing a React Application utilizing React-Router@4, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5e7d0d4d6c198fddac198f9dad4d1d0c7f5869bd7d0c1d49b83">[email protected]</a> ...

Implementing a custom arrow icon and adding functionality for closing on click in Kendo Multiselect

I'm looking to enhance the functionality of my Kendo Multiselect by giving it the appearance and behavior of a standard dropdown list. I'd like to include an arrow or triangle icon that toggles and closes the list when clicked. Can anyone provide ...

ERROR: JSON parsing failed due to an unexpected token "<", indicating an issue with the syntax and structure of the input data

Currently, I am following a tutorial on Scrimba to learn about React and React Router 6. Unfortunately, I have encountered an error with the data provided in the tutorial. The error message reads as follows: 67:1 Uncaught (in promise) SyntaxError: Unexpect ...

What is the best way to print a webpage that has a background image?

Currently facing an issue while trying to print a web page form in IE that has a background-image. Despite attempting multiple tricks, the background-image is not showing in the print preview. If anyone has successfully resolved this problem before, your ...

What could be causing the JavaScript error in this code snippet?

Check out this code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Cool App</title> </head> <body> <p id='nameDisplay'> Name Display Area </p> ...

Converting XML data from Oracle to JSON format in Postgres

I need assistance with migrating Oracle code to PostgreSQL. In Oracle, we use XML while in PostgreSQL we use JSON. I am facing challenges with some basic aspects during the migration process, For instance, in Oracle, We have a function called newDOMDocum ...

Is it possible to modify an HTML element when hovering over it in an ASP.Net page?

Is there a way to use jQuery to show the child span text - SomeClassChild3 string when hovering over the parent div - SomeClassParent in an aspx page? Here is the JavaScript section of the code: function ShowDiv(Somedata){ for(var v in Somedata){ va ...

Scroll through Two DIVs, where one is displayed and the other is concealed

Check out my JSFiddle here: https://jsfiddle.net/rq2tvccg/14/ I'm working on a project with 2 DIVs that each contain elements. Only one of the DIVs is displayed at a time, toggled by a button. I need to add an element that appears in both lists simul ...

Sending an object and receiving it in an Angular modal window

I am struggling to pass Objects into a modal. I am unsure how to pass an argument into a modal, so I am attempting the following: vm.viewGroupDetail = function(userDetails) { var scope = $scope.$new(); scope.userDetails = userDetails; vm.mod ...

PHP API Integration for XBox

Check out this demo link: http://davidwalsh.name/xbox-api I decided to create a php file with the following content.. <?php // Customizations $gamertag = 'RyanFabbro'; $profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamert ...

Mastering the art of MUI V4: Implementing conditional row coloring

I've encountered an issue with my basic Material UI v4 datagrid. I'm attempting to change the color of any row that has an age of 16 to grey using color: 'grey'. However, I'm finding it challenging to implement this. The documentat ...

What is the best way to execute a jQuery method once WordPress posts have finished loading?

I am currently utilizing the Smooth Div Scroll jQuery Plugin to create a dynamic filmstrip feature on a website. The film strip consists of images pulled from a custom post type, each with its own title and single image. The plugin allows for horizontal sc ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

My AJAX function is not functioning as intended

I'm currently developing a time management system for my workplace. As I was coding, I implemented a feature that allows users to configure the database details similar to the setup process in WordPress. Once the data is saved successfully, I aim to d ...

Obtaining objects from a Meteor collection on the server triggers a "Must have Fiber to proceed" error

As a beginner in creating meteor apps, I am working on a project that involves querying git issues from a specific repository. The goal is to generate tasks from these issues after retrieving them using the Github API. However, I keep encountering an error ...

What is the best way to convert tags into links efficiently using JavaScript?

Suppose I have a block of HTML code as follows: Greetings, I am a #robot and this is my #home. Is there a way to transform it into: Greetings, I am a <a href="blah.com/robot" class="tag">#robot</a> and this is my <a href="blah.com/home" ...

Issue with Bower not adhering to bower.json specifications during installation

https://i.sstatic.net/tJocZ.png Everything you need to know is in the image - I am attempting to install a specific version of angular-bootstrap. When I execute: bower install angular-bootstrap#0.13.0 --save it asks for my resolution answer, even though ...

Utilizing async parallel for executing multiple queries

Hey there, I'm new to Javascript and I've been trying to work with the async.parallel function. I have a specific task where I am fetching data from my database and storing it in an array called "reviewArr." Then, I want to return this array of ...

Modifying npm packages within a web application

I have a web application where I recently installed an npm package. However, I've realized that I need to customize it by adding some code. My attempt to modify the package directly in node_modules hasn't resulted in any visible changes. Is there ...