我正在使用 Visual Studio 2022 asp.net Razor 页面项目,并尝试将所选记录的 DataTables.net 表中的数组传递回 .cshtml.cs OnPostRemove。看来正在传递数组,有效负载看起来正确,并且 OnPostRemove 参数具有正确的计数,但所有字段均为空。
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;
}
datatables.net 表的 JavaScript
<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>
Payload 显示了数组,但是当它到达 OnPostRemove 时,值都是 NULL。这是我的第一个项目,所以我希望我错过了一些明显的东西。
通过添加 {get; 解决了这个问题设置;}到每个班级项目:
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; }
}