Reputation: 47
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();
}
}
Upvotes: 1
Views: 642
Reputation: 360
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.
Upvotes: 1