I'm using Visual Studio 2022 asp.net Razor pages project and trying to pass an array from a DataTables.net table of selected records back to .cshtml.cs OnPostRemove. It appears that the array is being passed, payload looks correct, and the OnPostRemove parameter has the correct count, but all fields are null.
OnPostRemove showing empty list
public List<RemoveAirports> ListAirports = new List<RemoveAirports>();
public void OnPostRemove([FromBody] List<RemoveAirports> removeAirports)
{
if(removeAirports == null)
{
Console.WriteLine("Empty");
}
Console.WriteLine("Not Empty");
}
public class RemoveAirports
{
public string continentName;
public string countryName;
public string regionName;
public string regionCode;
public string airport;
public string airportName;
}
JavaScript for datatables.net table
<script>
$(document).ready(function () {
var table = $('#assignedAirports').DataTable({
columns: [
{name: "id", title: "Select"},
{ name: "continentName", title: "Continent Name"},
{ name: "countryName", title: "Country Name" },
{ name: "regionName", title: "Region Name"},
{ name: "regionCode", title: "Region Code" },
{ name: "airport", title: "Airport" },
{ name: "airportName", title: "Airport Name" }
],
dom: 'Bfrtip',
buttons: [
{
className: "btn-outline-danger",
text: "Remove All Selected Airports",
action: function (e, dt, node, config) {
var removeAirports = dt.rows({ selected: true }).data().toArray();
removeAirports = JSON.stringify(removeAirports);
$.ajax({
type: "POST",
url: window.location.href + "&handler=Remove",
data: removeAirports,
dataType: "json",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
}
}
],
columnDefs: [{
targets: 0,
data: null,
defaultContent: '',
orderable: false,
className: 'select-checkbox',
},
{
targets: 1,
visible: true
}],
select: {
style: 'multi',
selector: 'td:first-child'
},
order: [[1, 'asc']]
});
$(document).ready(function () {
var DT1 = $('#assignedAirports').DataTable();
$(".selectAll").on("click", function (e) {
if ($(this).is(":checked")) {
DT1.rows({ search: 'applied' }).select();
} else {
DT1.rows({ search: 'applied' }).deselect();
}
});
})
});
</script>
The Payload shows the array, but when it gets to the OnPostRemove the values are all NULL. This is my first project so I'm hoping I have just missed something obvious.
This was resolved by adding {get; set;} to each class item:
public class RemoveAirports
{
public string id { get; set; }
public string continentName { get; set; }
public string countryName { get; set; }
public string regionName { get; set; }
public string regionCode { get; set; }
public string airport { get; set; }
public string airportName { get; set; }
}