I am working on a blazor client-side project using asp.net core 3.1. and would like to use code-behind class. I found an example that handles this topic, but I believe it is outdated and not related to client-side blazor.
Here is an example
@functions
{
[Parameter]
string Id { get; set; }
string PageTitle { get; set; }
Book CurrentBook { get; set; }
protected override async Task OnParametersSetAsync()
{
if (Id == null || Id == "0")
{
PageTitle = "Add book";
CurrentBook = new Book();
}
else
{
PageTitle = "Edit book";
await LoadBook(int.Parse(Id));
}
}
private async Task LoadBook(int id)
{
CurrentBook = await Http.GetJsonAsync<Book>("/Books/Get/" + id);
}
private async Task Save()
{
await Http.PostJsonAsync("/Books/Save", CurrentBook);
UriHelper.NavigateTo("/");
}
}
Now I want to move this code from razor page to code behind that would look like this
public class EditBookModel : BlazorComponent
{
[Inject]
protected IUriHelper UriHelper { get; set; }
[Inject]
protected HttpClient Http { get; set; }
[Parameter]
protected string Id { get; private set; } = "0";
protected string PageTitle { get; private set; }
protected Book CurrentBook { get; set; }
protected override async Task OnParametersSetAsync()
{
if (Id == null || Id == "0")
{
PageTitle = "Add book";
CurrentBook = new Book();
}
else
{
PageTitle = "Edit book";
await LoadBook(int.Parse(Id));
}
}
protected async Task LoadBook(int id)
{
CurrentBook = await Http.GetJsonAsync<Book>("/Books/Get/" + id);
}
protected async Task Save()
{
await Http.PostJsonAsync("/Books/Save", CurrentBook);
UriHelper.NavigateTo("/");
}
}
Unfortunately there is no BlazorComponent to inherit from ie. OnParametersSetAsync is unavailable.
Any suggestions how to make this work?