Using datatables.net with server-side Blazor application

徘徊边缘 提交于 2021-01-05 07:09:53

问题


I'm trying to use datatables.net with my server-side Blazor application and any help would be appreciated.

I've tried the code mentioned half-way down https://datatables.net/forums/discussion/56389/datatables-with-blazor, however, the problem I'm having is that certain UI elements such as paging are being replicated when I browse between pages.

Below is my _Host.cshtml file

@page "/"
@namespace MyApplication.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MyApplication.Web</title>
    <base href="~/" />
    <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
    <link href="css/site.css" rel="stylesheet" />    

    <script src="/lib/jquery/jquery.min.js"></script>
    <script src="/lib/datatables/js/jquery.dataTables.min.js"></script>
    <link href="/lib/datatables/css/jquery.dataTables.min.css" rel="stylesheet" />

</head>
<body>
    <app>
        <component type="typeof(App)" render-mode="ServerPrerendered" />
    </app>

    <div id="blazor-error-ui">
        <environment include="Staging,Production">
            An error has occurred. This application may no longer respond until reloaded.
        </environment>
        <environment include="Development">
            An unhandled exception has occurred. See browser dev tools for details.
        </environment>
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>   

    <script>
        function AddDataTable(table) {
            $(document).ready(function () {
                $(table).DataTable({
                    "searching": false
                });
            });
        }
    </script>

    <script>
        function RemoveDataTable(table) {
            $(document).ready(function () {
                $(table).DataTable().destroy();
            });
        }
    </script>

    <script src="_framework/blazor.server.js"></script>

</body>
</html>

Below is the code from the razor component

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MyApplication.Shared.Entities;
using MyApplication.Web.Interfaces;

namespace MyApplication.Web.Pages.Admin
{
    public partial class ListAdministrators
    {
        [Inject]
        public IAdministratorDataService AdministratorDataService { get; set; }

        [Inject]
        public NavigationManager NavigationManager { get; set; }

        public List<Administrator> Administrators { get; set; }

        protected override async Task OnInitializedAsync()
        {
            Administrators = (await AdministratorDataService.GetAll()).ToList();
        }

        protected void NavigateToAddAdministrator()
        {
            NavigationManager.NavigateTo("/Admin/AdministratorEdit");
        }

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

One thing to point out is that on https://datatables.net/forums/discussion/56389/datatables-with-blazor they have the function RemoveDataTable which I have in the code above however, I'm not sure how this function can be called outside of a button click.

First load - all good

Browse to home - Paging UI elements still showing


回答1:


I seem to have resolved the repeating UI elements issue with the below approach however I'd be interested to know whether there is a better approach, actually, I'm sure there must be so perhaps the question should be how bad is the below approach?

_Host.cshtml now has the below added

<script src="~/scripts/JSInterop.js"></script>
<script src="/lib/jquery/jquery.min.js"></script>
<script src="/lib/datatables/js/jquery.dataTables.min.js"></script>
<link href="/lib/datatables/css/jquery.dataTables.min.css" rel="stylesheet" />

Created a new component DataTable.razor

@inject Microsoft.JSInterop.IJSRuntime JSRuntime;

    <div id="@id">
        @ChildContent
    </div>

@code
{
    [Parameter]
    public bool Searchable { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    private string id { get; set; } = "DataTable-" + Guid.NewGuid().ToString();


    protected override void OnParametersSet()
    {
        StateHasChanged();
        base.OnParametersSet();
    }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        await JSRuntime.InvokeAsync<string>("AddDataTable", new object[] { "#" + id + " table", Searchable });
        await base.OnAfterRenderAsync(firstRender);
    }
}

Created a simple JS file JSInterop.js

function AddDataTable(table, searching) {    
    $(table).DataTable({
        "searching": searching
    });    
}

I then use the below code when creating a datatable on the page

<DataTable Searchable="true">
        <table class="table">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Access Level</th>
                    <th>Date Added</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var administrator in Administrators)
                {
                    <tr>
                        <td>@administrator.Id</td>
                        <td>@administrator.LastName</td>
                        <td>@administrator.AccessLevel.GetDisplayName()</td>
                        <td>@administrator.DateCreated.ToShortDateString()</td>
                        <td>
                            <a href="@($"Admin/EditAdministrator/{administrator.Id}")" class="btn btn-primary table-btn">
                                Edit
                            </a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </DataTable>


来源:https://stackoverflow.com/questions/62176800/using-datatables-net-with-server-side-blazor-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!