Я сделал это вот так,
В DataTable я добавил
- dataSr c
- columnDefs
In HTML, я добавил
- 4-й заголовок таблицы
В бэкэнд-контроллере я возвращаю именованный массив booksData
в DataTable ajax call
@section scripts {
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#DT_load').DataTable({
"ajax": {
"url": "https://localhost:44333/Home/Data",
"type": "GET",
"datatype": "json",
"dataSrc": "booksData"
},
"columns": [
{ "data": "name", "width": "30%" },
{ "data": "author", "width": "30%" },
{ "data": "isbn", "width": "30%" },
{ "data": "id", "width": "10%" }
],
"columnDefs": [
{
"targets": 3,
"data": "id",
"render": function (data) {
return '<a href="' + data + '">Download</a>';
}
}
],
"language": {
"emptyTable": "No Data Found"
},
"width": "100%"
});
});
</script>
}
@if (Model.Count() > 0)
{
<table class="table table-striped border">
<tr class="table-secondary">
<th>
<label>@Model.First().Name</label>
</th>
<th>
<label>@Model.First().Author</label>
</th>
<th>
<label>@Model.First().ISBN</label>
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(m => item.Name)
</td>
<td>
@Html.DisplayFor(m => item.Author)
</td>
<td>
@Html.DisplayFor(m => item.ISBN)
</td>
<td>
<a asp-route-id="@item.Id" class="btn btn-success btn-sm">Edit</a>
</td>
</tr>
}
</table>
<div class="col-12" style="text-align: center">
<br />
<span class="h3 text-info">OR</span>
<br />
<div class="col-12 border p-3">
<table id="DT_load" class="table table-stripped table-bordered" style="width: 100%">
<thead>
<tr>
<th>Name</th>
<th>Atuhor</th>
<th>ISBN</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
}
else
{
<p>No Books Available</p>
}
public class HomeController : Controller
{
public IActionResult Index()
{
var books = new List<Book> { new Book { Id=1, Name="Abcd", Author="Xyz", ISBN="1234" },
new Book { Id=2, Name="Efgh", Author="Igm", ISBN="7896" },
new Book { Id=3, Name="Qrty", Author="Ght", ISBN="8791" },};
return View(books);
}
public IActionResult Data()
{
var books = new List<Book> { new Book { Id=1, Name="Abcd", Author="Xyz", ISBN="1234" },
new Book { Id=2, Name="Efgh", Author="Igm", ISBN="7896" },
new Book { Id=3, Name="Qrty", Author="Ght", ISBN="8791" },};
return Json(new { booksData = books });
}