尝试从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#中的MODEL:
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());
},
要发送对象列表,您需要形成数据,例如示例(填充列表对象),以及:
数据:{模型:列表},
类型:“ post”,