What I did when trying to send some data from several selected rows in DataTable to MVC action:
HTML
At the beginning of a page:
@Html.AntiForgeryToken()
(just a row is shown, bind from model):
@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>
}
Button which starts the JavaScript function:
<button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
JavaScript function:
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 action:
[HttpPost]
[ValidateAntiForgeryToken] //<--- This is important
public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
And MODEL in 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; }
}
CONCLUSION:
The reason for ERROR:
"Failed to load resource: the server responded with a status of 400 (Bad Request)"
Is attribute: [ValidateAntiForgeryToken]
for the MVC action StartWorkflow
Solution in Ajax call:
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
To send List of objects you need to form data like in example (populating list object) and:
data: { model: list },
type: "post",