Blazor WebAssembly - "DataTable is not a function" error when changing menu
Blazor WebAssembly - "DataTable is not a function" error when changing menu
Hi,
When I changed from one menu (for example href="/datatable") to another menu (for example href="/non-datatable"), and then back to /datatable, the table shows error:
jQuery.Deferred exception: $(...).DataTable is not a function
TypeError: $(...).DataTable is not a function
It seems like the web forgot about the function and javascript all of sudden. It did not happened when loading the table the first time. There is nothing wrong with the jQuery since it passed on the document ready function.
Thank you.
// JavaScript ////////////////////////////////////////////////////
function addDT_Employees(table) {
$(document).ready(function () {
$(table).DataTable({ // error here
"columnDefs": [{
"targets": 0,
"orderable": false,
"width": "5%"
}],
"order": [[1, "asc"]],
"pageLength": 10,
"lengthMenu": [[5, 10, 25, 50, 100, -1], [5, 10, 25, 50, 100, "All"]]
});
});
}
// Razor File ////////////////////////////////////////////////////
protected async override Task OnAfterRenderAsync(bool firstRender)
{
try
{
if (firstRender)
{
// Set DataTable
await JS.InvokeVoidAsync("addDT_Employees", "#tableEmployees");
}
} catch (Exception ex)
{
}
}
Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.
Answers
As you say, that suggests that the DataTable JS file is no longer loaded.
We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.
Cheers,
Colin
Hi.
This error also appears when making a call with the tag to a jQuery library (jquery-3.6.3.js) after making the call to DataTables.js. That is why the call to DataTables.js must come after.