i'm using datatables.net in my razor page and i have a dropdown which postback to change the data in the datatable below is the code
$(document).ready(function () {
//$("#taskDt").DataTable();
var table = $("#taskDt").DataTable({
paging: true,
responsive: true,
searching: true,
ordering: true,
order: [[1, "asc"]]
});
$("#ddlGroup").change(function(){
var a= $("#ddlGroup Option:Selected").text();
var b= $("#ddlGroup Option:Selected").val();
//alert(b);
//this.form.submit();
$.ajax({
//dataType: 'json',
url: '/page/Index?handler=GET',
type: 'GET',
dataType: "text",
data: { "Id": b },
processing: true,
serverSide: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
console.log(data);
//table.ajax.reload();
$('#taskDt').DataTable().ajax.reload(true)
//$('#taskDt').DataTable().ajax.reload();
},
error: function () {
alert("AJAX Request Failed, Contact Support");
}
});
})
well the data returned is the full html page and i get an error of invalid JSON and when i set dataType: "JSON" if fails and alerts ajax request failed
any help will be much appreciated.
Here is a demo to show how to update datatable data when dropdown changes:
Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
TestDataTable.cshtml:
<select id="ddlGroup">
<option>Choose Id</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table id="taskDt">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody></tbody>
</table>
@section scripts{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script>
var table;
function LoadData() {
table = $("#taskDt").DataTable({
"ajax": {
url: '?handler=GET',
type: 'GET',
processing: true,
serverSide: true,
},
"columns": [
{ "data": "id", "width": "50%" },
{ "data": "name", "width": "50%" },
],
paging: true,
responsive: true,
searching: true,
ordering: true,
order: [[1, "asc"]]
});
}
$(document).ready(function () {
LoadData();
})
$("#ddlGroup").change(function () {
table.ajax.url("?handler=GET&&Id=" + $("#ddlGroup Option:Selected").val()).load();
});
</script>
}
TestDataTable.cshtml.cs(I use fake data to test):
public class TestDataTableModel : PageModel
{
public void OnGet()
{
}
public JsonResult OnGetGet(int? Id)
{
List<Test> l = new List<Test>();
if (Id == null)
{
l = new List<Test> { new Test { Id = 1, Name = "1" }, new Test { Id = 2, Name = "2" },new Test { Id = 3, Name = "3" } };
}
else
{
l = new List<Test> { new Test { Id = Convert.ToInt32(Id), Name = Id+"" }};
}
return new JsonResult(new { draw = 1, recordsFiltered = l.Count(), recordsTotal = l.Count(), data = l });
}
}