【问题标题】:After submitting EditForm, component does not rerender提交EditForm后,组件不重新渲染
【发布时间】:2020-08-17 12:58:48
【问题描述】:

美好的一天!

我使用 Blazor 组件来呈现和更新非 sql 数据库信息。我希望在提交后重新渲染组件,但是,即使在调用this.StateHasChanged(); 之后,我也必须手动刷新页面。我的代码没有错误或警告消息。

在阅读了 Blazor 和 ASP.net 官方文档,大量关于 stackoverflow 的教程和答案后,我仍然不明白为什么组件不刷新。

我还尝试使用控制变量和if() 语句手动刷新组件的内容。

谢谢!

@page "/admin/selectcategory"

<h5>SelectCategory</h5>

@{
    int count = categoryList.Count;
    if (count != 0)
    {
        <div class="list-group list-group-flush mt-3 mb-5">
            @foreach (var rec in categoryList)
            {
                <a href="Category/@rec.ID" class="list-group-item list-group-item-action pl-0 py-4">
                    <div class="d-flex justify-content-between">
                        <h5 class="mb-1 mt-2">@rec.Name</h5>
                        <small>500 anunturi</small>
                    </div>
                    <p class="mt-1">@rec.Description</p>
                    <small class="text-muted">Lorem, Ipsum, Dolor sit, Amet...</small>
                </a>
            }
        </div>
    }
    <h3 class="panel-title my-2">Add Category</h3>
    <p>Lorem ipsum dolor sit amet</p>
    <EditForm Model="@newCategory" OnValidSubmit="AddCategory"
              class="my-3">
        <InputText @bind-Value="newCategory.Name"
                   class="form-control py-3 px-3 my-2"
                   id="new-category-name"
                   placeholder="Category Name" />
        <InputTextArea @bind-Value="newCategory.Description"
                       class="form-control py-3 px-3 my-2"
                       id="new-category-description"
                       placeholder="Description" />
        <button type="submit" class="btn btn-light py-2 px-3 my-2">Create Category</button>
    </EditForm>
}

@code{
    private List<Category> categoryList = new List<Category>();
    private Category newCategory = new Category();
    private Category cat = new Category();
    protected override async Task OnInitializedAsync() => categoryList = await Task.Run(() => cat.Read("CategoryList"));

    private async Task AddCategory()
    {
        await Task.Run(() => newCategory.Create("CategoryList"));
        newCategory = new Category();
        this.StateHasChanged();

【问题讨论】:

    标签: c# asp.net blazor blazor-server-side asp.net-blazor


    【解决方案1】:

    您没有在创建后将项目添加到列表中。或者您应该再次调用 OnInitializedAsync() 中的相同代码。这就是它在刷新时显示的原因。

    【讨论】:

    • 感谢您快速回答我的问题。添加将新对象附加到列表中修复了它。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2018-08-12
    • 2019-01-24
    • 1970-01-01
    • 2021-12-06
    • 2019-12-27
    相关资源
    最近更新 更多