gpt4 book ai didi

javascript - 使用 $.post 将 javascript 数组传递到 c# 数组/列表,而不将数据类型指定为 json

转载 作者:行者123 更新时间:2023-12-03 01:12:24 24 4
gpt4 key购买 nike

我用 JavaScript 创建了一个模型,如下所示

function Vehicle() {
this.type = 'Vehicle';
this.data = {
VehicleKey: null
}
};

我在 C# 中创建了一个类似的模型,如下所示

public class Vehicle
{
public string VehicleKey { get; set; }
}

现在我正在 JavaScript 中构建一个 VehicleKeys 数组,如下所示

function GetVehicleDetails(inputarray) {

var vehicleKeys = [];

for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = new Vehicle();
vehicleObject.data.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKey.push(vehicleObject.data);
}
return vehicleKeys ;
}

我按如下方式调用$.post(url, data)

var objectToSend = GetVehicleDetails(selectedVehicles);

var data = JSON.stringify({
'vehicles': objectToSend
});

$.post(url, data)
.done(function (result) {
if (result) {
download(result, 'VehicleReport.xlsx', { type: 'application/octet-stream' });
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function (error) {
console.log("Error creating report.");
});

MVC Controller 有一个方法可以接受来自 javascript 的具有多个 VehicleKeysVehicle

public byte[] CreateVehicleReport(List<Vehicle> vehicles)
{
//Generation of report and pass it back to javascript
}

在这里,我可以在 javascript 中提交 Vehicles 的数据为 10 和 11,但是当它捕获 c# 时,计数为 0。

任何帮助将不胜感激。

最佳答案

$.post 未发布 Content-Type json 数据,因此需要使用 $.ajax

    function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = {}; // Set Object
vehicleObject.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKeys.push(vehicleObject);
}
return vehicleKeys;
}

var objectToSend = GetVehicleDetails(selectedVehicles);

$.ajax({ type: 'POST',
url: url,
data: JSON.stringify(objectToSend),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('data: ' + data);
},
}).done(function () {
if (result) {
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function () {
console.log("Error creating report.");
});

C# 方法

[HttpPost("CreateVehicleReport")]
public byte[] CreateVehicleReport([FromBody]List<Vehicle> vehicles)
{
return null;
//Generation of report and pass it back to javascript
}

关于javascript - 使用 $.post 将 javascript 数组传递到 c# 数组/列表,而不将数据类型指定为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52161792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com