I'm trying to create a register account page in Blazor Web App. I need the form submission callback to run on the client as it needs to set the authentication cookie, but I can't manage to achieve this.
This is my current component code:
@using ClassLibrary.Models.Auth
@using ClassLibrary.Models.Database
@using ClassLibrary.Localization.Shared.Forms
@using IDFW.Models.HttpClients
@rendermode InteractiveWebAssembly
@page "/auth/register"
@inject IStringLocalizer localizer
@inject ApiHttpClient api
@localizer["PageTitle"]
@((MarkupString)localizer["FormHint"].Value)
@code {
private RegisterModel RegisterModel { get; set; } = null!;
private EditContext editContext = null!;
private ValidationMessageStore validationMessageStore = null!;
private bool isProcessing = false;
[Inject]
private NavigationManager navigation { get; set; } = null!;
protected override void OnInitialized()
{
RegisterModel ??= new();
editContext = new(RegisterModel);
validationMessageStore = new(editContext);
editContext.OnFieldChanged += (_, args) =>
{
validationMessageStore.Clear(args.FieldIdentifier);
editContext.NotifyValidationStateChanged();
};
}
private async Task HandleOnValidSubmit()
{
isProcessing = true;
validationMessageStore.Clear();
// Try register account
HttpResponseMessage res = await api.HttpClient.PostAsJsonAsync("auth/register", RegisterModel);
if (res.IsSuccessStatusCode)
{
navigation.NavigateTo("/");
}
else if (res.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
HttpValidationProblemDetails problemDetails = (await res.Content.ReadFromJsonAsync())!;
if (problemDetails.Errors != null)
{
foreach (KeyValuePair message in problemDetails.Errors)
{
FieldIdentifier fieldIdentifier = new(RegisterModel, message.Key);
validationMessageStore.Add(fieldIdentifier, message.Value);
}
editContext.NotifyValidationStateChanged();
}
}
isProcessing = false;
}
}
I want everything in the page to be rendered on the server as well as realtime data validation, except HandleOnValidSubmit() to run on the client. I tried using the InteractiveWebAssembly rendermode, but apparently it's not the right approach or I'm doing something wrong.