So a recent project with Blazor required that we keep with HTML tables to display data. The JS DataTables provides a sexy way of displaying data on a web page. DataTables provide pagination, search and data sorting by default, and a ton of other useful options.

If you have tables with data that update dynamically, I will suggest using an alternative option.

With Blazor all of your Javascript code needs to placed or imported in the base _host.cshtml file. We then use IJSRuntime to call the JavaScript functions from your Razor pages.

When we navigate away from the page with the DataTables, we have to manually destroy the rendered element of the DataTable. If we do not remove this manually, the pagination and search element will remain on the page.

The complete project can be viewed on Github, see bottom of the page for link

Add the following lines to the “Head” portion of your “_Host.cshtml” Page. This is to import the required jquery library’s for the DataTables to work:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

Add the following JavaScript entry just below the start of your Body tag:

<script>
        function TestDataTablesAdd(table) {
            $(document).ready(function () {
                $(table).DataTable();
            });
        }
        function TestDataTablesRemove(table) {
            $(document).ready(function () {
                $(table).DataTable().destroy();
                // Removes the datatable wrapper from the dom.
                var elem = document.querySelector(table + '_wrapper');
                elem.parentNode.removeChild(elem);
            });
        }
    </script>

TestDataTablesAdd gets called once the page is finished rendering. This transforms your normal table into the DataTable. TestDataTablesRemove gets called when you leave the page. This function deletes and removes all elements of the DataTable.

Now go to your Razor page and inject the following libraries into your page:

@inject IJSRuntime JSRuntime
@implements IDisposable

Now you can create your normal table with data. Make sure you allocate an ID to the table you want to transform into a DataTable:

<table class="table" id="example">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>

Then add the following code to the @Code section of your Razor page

@code {
    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {

        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);

    }
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await JSRuntime.InvokeAsync<object>("TestDataTablesAdd", "#example");
    }

    void IDisposable.Dispose()
    {
        JSRuntime.InvokeAsync<object>("TestDataTablesRemove", "#example");
    }
}

As mentioned before, OnAfterRenderAsync uses JSRuntime to call your TestDataTablesAdd JavaScript function when the page is finished rendering. The TestDataTablesRemove MavaScript function gets called by IDispose when you leave the page, removing all DataTable elements. Your table ID gets passed as a variable in the JSRuntime call and gets picked up by your JavaScript function to be used by the DataTable library.

Have any suggestions or constructive criticism? Feel free to send me a message.