我在尝试将一些数据从 DataTable 中的几个选定行发送到 MVC 操作时做了什么:
HTML 在页面的开头:
@Html.AntiForgeryToken()
(只显示一行,从模型绑定):
@foreach (var item in Model.ListOrderLines)
{
<tr data-orderid="@item.OrderId" data-orderlineid="@item.OrderLineId" data-iscustom="@item.IsCustom">
<td>@item.OrderId</td>
<td>@item.OrderDate</td>
<td>@item.RequestedDeliveryDate</td>
<td>@item.ProductName</td>
<td>@item.Ident</td>
<td>@item.CompanyName</td>
<td>@item.DepartmentName</td>
<td>@item.ProdAlias</td>
<td>@item.ProducerName</td>
<td>@item.ProductionInfo</td>
</tr>
}
启动 JavaScript 函数的按钮:
<button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
JavaScript 函数:
function ProcessMultipleRows() {
if ($(".dataTables_scrollBody>tr.selected").length > 0) {
var list = [];
$(".dataTables_scrollBody>tr.selected").each(function (e) {
var element = $(this);
var orderid = element.data("orderid");
var iscustom = element.data("iscustom");
var orderlineid = element.data("orderlineid");
var folderPath = "";
var fileName = "";
list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
});
$.ajax({
url: '@Url.Action("StartWorkflow","OrderLines")',
type: "post", //<------------- this is important
data: { model: list }, //<------------- this is important
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
showPreloader();
},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function () {
hidePreloader();
}
});
}
}
MVC 动作:
[HttpPost]
[ValidateAntiForgeryToken] //<--- This is important
public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
和 C# 中的模型:
public class WorkflowModel
{
public int OrderId { get; set; }
public int OrderLineId { get; set; }
public bool IsCustomOrderLine { get; set; }
public string FolderPath { get; set; }
public string FileName { get; set; }
}
结论:
错误的原因:
"Failed to load resource: the server responded with a status of 400 (Bad Request)"
是属性:[ValidateAntiForgeryToken]
对于MVC动作StartWorkflow
Ajax 调用中的解决方案:
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
要发送对象列表,您需要形成示例中的数据(填充列表对象),并且:
数据:{模型:列表},
类型:“帖子”,