1

I'm new with Blazor and I have a question. On page (Task OnInitializedAsync()) it will get the latest records from the database. However, when I add a new record how to display the record that is added, without going to another link/page?

@code {
    private List<ViewArticleModel> Articles;
    private NewArticleModel newArticle = new NewArticleModel();

    protected override async Task OnInitializedAsync()
    {
        var something = await _blogService.GetArticles();

        Articles = something.Select(x => x.ToModelView()).ToList();
    }

    private void AddNewArticle()
    {
        _blogService.AddNewArticle(newArticle.ToModel());

        newArticle = new NewArticleModel();

        OnParametersSetAsync();
    }
}

1 Answer 1

1

You have two options.

First is to put your DB calling code in new task

    protected override async Task OnInitializedAsync()
{

    await LoadData();
}

private async Task LoadData()
{
    var something = await _blogService.GetArticles();

    Articles = something.Select(x => x.ToModelView()).ToList();

    await InvokeAsync(StateHasChanged);

}

With this you can call LoadData() after you insert new record to the database and it will load all the records again.

The second way is to add your new record (newArticle) to the database but also to Articles list using code below and just call StateHasChanged to update UI

    private void AddNewArticle()
{
    _blogService.AddNewArticle(newArticle.ToModel());

    newArticle = new NewArticleModel();

    OnParametersSetAsync();

    ----> Articles.Add(newArticle)
    
    ----> await InvokeAsync(StateHasChanged);

}

The second way is more efficient as it doesn't need to read nothing from the database after you insert new record.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.