I’m trying to define a component which acts as a bootstrap alert wrapper.
BootstrapAlert.razor
<div class="alert alert-@AlertType d-@(string.IsNullOrEmpty(Message) ? "none" : "block")" role="alert">
@Message
</div>
@code {
[ParameterAttribute]
private string AlertType { get; set; } = "info"; // Default alert type
[ParameterAttribute]
private string? Message { get; set; }
// Method to update the alert type and message
public async Task ShowAsync(string alertType, string message)
{
AlertType = alertType;
Message = message;
await InvokeAsync(StateHasChanged);
}
// Method to hide the alert
public async Task HideAsync()
{
Message = null;
await InvokeAsync(StateHasChanged);
}
protected override async Task OnParametersSetAsync()
{
//Message is ALWAYS null here
await base.OnParametersSetAsync();
}
}
Page:
<form class="row" @onsubmit="SubmitForm" @onsubmit:preventDefault>
<Alert @ref=SaveAlert></Alert>
<button type="submit">Save</button>
</form>
@code {
private Alert? SaveAlert;
private async Task SubmitForm()
{
try
{
await SetIsLoading(true); //DISPLAYS A LOADING SPINNER
if (SaveAlert != null) await SaveAlert.HideAsync();
//.......
if (SaveAlert != null) await SaveAlert.ShowAsync("success", "OK");
}
catch (Exception ex)
{
if (SaveAlert != null) await SaveAlert.ShowAsync("danger", ex.Message);
}
finally
{
await SetIsLoading(false);
}
StateHasChanged();
}
}
The alert component is never updated, at “OnParametersSetAsync” the “Message” parameter is always null.
I have tryed not async versions of the methods, putting “StateHasChanged” everywhere, not calling the “Hide” method, also removing the [ParameterAttribute] attributes so it were used as a regular variables but nothing seems to work for me
I’m pretty new at blazor so I don’t know what else could be relevant. I’m using the app as RenderMode=”Server”
What I’m doing wrong?