Search code examples
asp.net-coreblazor

modal?.ShowAsync() throwing an error when called in OnInitializedAsync() to generate a Modal


I am trying to open a Modal on the initialization of a blazor page. I have used below code to generate the Modal. When I am using OnClick function it is being pop-up correctly but when the same function is being called inside OnInitializedAsync() it is throwing an error of Object reference not set to an instance of an object.

ShowModal.razor

<Modal @ref="modal" Title="Modal title">
    <BodyTemplate>
        @sMessage
    </BodyTemplate>
    <FooterTemplate>
        <Button Color="ButtonColor.Secondary" @onclick="OnHideModalClick">Close</Button>
    </FooterTemplate>
</Modal>

@*  <Button Color="ButtonColor.Primary" @onclick="OnShowModalClick">Show Modal</Button>  *@

@code {

    [CascadingParameter]
    public string sMessage { get; set; }

    [CascadingParameter]
    public bool bShowModal { get; set; } = false;


    private Modal modal;

    protected override async Task OnInitializedAsync()
    {
        await OnShowModalClick();
    }

    private async Task OnShowModalClick()
    {
        await modal?.ShowAsync();
    }
    private async Task OnHideModalClick()
    {
        await modal?.HideAsync();
    }
}
ListMail.razor


<CascadingValue  Value="@sMessageModal">
    <ShowModal></ShowModal>
</CascadingValue>

I am expecting to pop Modal using modal?.ShowAsync() on the initialization of the blazor page.enter image description here I have attached image of the error


Solution

  • Firstly, I can reproduce your issue in my sample using Blazor.Bootstrap Modal. Like you can see, this is resulting from the null value for modal parameter.

    enter image description here

    In short, when we call OnInitializedAsync, the parameter hasn't been initialized, so we need call the OnShowModalClick method later than OnInitiaized. Here I had a test with OnAfterRenderAsync and it worked well.

    enter image description here