Search code examples
c#asp.netblazorblazor-server-sideasp.net-blazor

After submitting EditForm, component does not rerender


Good day!

I use Blazor component for rendering and updating non-sql database information. I expected the re-rendering of the component after submission, but, even after calling this.StateHasChanged();, I have to manually refresh the page. My code does not have errors or warning messages.

After reading the official Blazor and ASP.net documentation, lots of tutorials and answers on stackoverflow, I still can not figure why the component is not refreshing.

I also manually tried to refresh the component's content using a control variable and if() statements.

Thank you!

@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();


Solution

  • Your not adding the item to the list after create. Or you should call the same code you have in OnInitializedAsync() again. Which is why it is showing on refresh.