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)
});