Home > Software engineering >  Wrong sequence of events in Blazor
Wrong sequence of events in Blazor

Time:06-14

I have a Blazor server-side application. In the code-behind in .razor.cs of a component I have

    protected override async Task OnInitializedAsync()
    {
        ...

        _role = await Authorization.GetCurrentUserRoleAsync();
        QuoteModel = await QuotesDb.GetQuoteByIdAsync(_role, QuoteId);

In the .razor:

@if((DateTime.Now - QuoteModel.Date).TotalDays > 60)
{
    ... do something
}

When the application is run,

_role = await Authorization.GetCurrentUserRoleAsync();

in the code-behind is executed, and then in razor

@if((DateTime.Now - QuoteModel.Date).TotalDays > 60)

is executed, before QuoteModel is instantiated in code-behind, which of course causes a null reference exception.

How can I make sure QuoteModel is instantiated before it is used?

CodePudding user response:

You can handle that with a null check:

@if(QuoteModel != null && DateTime.Now - QuoteModel.Date).TotalDays > 60)
  • Related