0

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?

1 Answer 1

1

You can handle that with a null check:

@if(QuoteModel != null && DateTime.Now - QuoteModel.Date).TotalDays > 60)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.