首页 > 解决方案 > 使用 Blazor 和 C# 刷新 html 表数据

问题描述

我有一种情况,我有一个 for 循环,它从我的数据模型中创建我的 html 表,该表从 SQL server express 获取数据。我想知道是否可以创建一个自动刷新方法,其中表数据只刷新而不是整个页面,如果没有,那么可能是 OnClick 按钮将从数据模型中检索最新数据并相应地更新表的方法。

我是 blazor 和 C# 的新手,因此将不胜感激,我当前的页面结构目前如下所示:

@page "/employees"

@using DataLib;

@inject IEmployeeData _db

@if (employees is null)
{
    <p style="color:white;"><em>Loading . . .</em></p>
}
else
{
    <table class="table" id="myTable">
        <thead>
            <tr>
                <th>Entry Date</th>
                <th>Employee</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var employee in employees)
            {
                <tr>
                    <td>@employee.EntryDate</td>
                    <td>@employee.POI</td>
                </tr>
            }
        </tbody>
    </table>
}

@code{
    private List<EmployeeModel> employees;

    protected override async Task OnInitializedAsync()
    {
        employees = await _db.GetEmployee();
    }

}

当我加载此页面和手动刷新时,上述内容非常完美。

有什么方法可以帮助我吗?

谢谢。

标签: c#htmlblazorblazor-server-side

解决方案


不确定这是您可以尝试的目标对接;

@inject IEmployeeData _db

@if (employees is null)
{
    <p style="color:white;"><em>Loading . . .</em></p>
}
else
{
    <table class="table" id="myTable">
        <thead>
            <tr>
                <th>Entry Date</th>
                <th>Employee</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var employee in employees)
            {
                <tr>
                    <td>@employee.EntryDate</td>
                    <td>@employee.POI</td>
                </tr>
            }
        </tbody>
    </table>

    <button @onclick="GetEmployees"> Refresh Employee List</button>
}


@code{
    private List<EmployeeModel> employees;

    protected override async Task OnInitializedAsync()
    {
        GetEmployees()

}

    private async void GetEmployees()
    {
        employees.Clear();

        employees = await _db.GetEmployee();

        StateHasChanged();
    }

祝你好运,


推荐阅读