I am trying to use JQuery datatable in my blazor project. I am using the CDN files to load the framework. This is my _Host.cshtml file:
@page "/"
@namespace Blazor.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blazor</title>
<base href="~/" />
<environment include="Development">
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
asp-fallback-href="css/bootstrap/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
crossorigin="anonymous"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" />
</environment>
<link href="css/site.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/jq-3.3.1/dt-1.10.18/datatables.min.css" />
</head>
<body>
<app>
@(await Html.RenderComponentAsync<App>
())
</App>
<script src="_framework/blazor.server.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jq-3.3.1/dt-1.10.18/datatables.min.js"></script>
<script>
$(document).ready(function () {
$('#carTable').DataTable();
});
</script>
</body>
</html>
And in my CarData.razor file I connect the ID like this:
<table id="carTable" class="display" style="width:100%">
When I run the application it doesn't load the framework. I get no error in my console.
I have read about Javascript interop in this documentation:
https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.0
Somehow it doesn't read my CDN files from the JQuery datatable.
Can someone point me in the right direction?
I have figured it out:
In my _Host.cshtml I have this code:
<script>
function DataTable() {
$(document).ready(function () {
$('#carTable').DataTable();
});
}
</script>
Then in my CarData.razor I call this method like this:
protected override async Task OnInitAsync()
{
await JSRuntime.InvokeAsync<object>("DataTable");
}
Don't forget to inject the library in your page:
@inject IJSRuntime JSRuntime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With