Sergey  Pitenko
Sergey Pitenko

Reputation: 353

NullReferenceException on page initialization if I use OnInitializedAsync method

I have a simple application but it stops working on page initialization with error

NullReferenceException: Object reference not set to an instance of an object. Site.Shared.MainLayout.BuildRenderTree(RenderTreeBuilder __builder) Error: enter image description here

But there is nothing complicated in the code. App.razor:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
  <NotFound>
      <LayoutView Layout="@typeof(MainLayout)">
          <p>Sorry, there's nothing at this address.</p>
      </LayoutView>
  </NotFound>

_Host.cshtml: enter image description here

MainLayout.razor: enter image description here

StartUpService.cs: enter image description here

page.GetPageGlobalAsync() is working well, I can pass this method in the debug mode. enter image description here

But after I have this error. And have no idea what is the reason and how can I get more information about what is wrong.

UPD

If I change code to:

PageGlobal page =  new PageGlobal()

And it started working but OnInitializedAsync is the async method, why I cannot use async-await methods in the OnInitializedAsync method?

Upvotes: 2

Views: 6280

Answers (2)

Gerrit
Gerrit

Reputation: 836

Your page is trying to render @pageGlobal.Title, before it's even got it from the async method. That's why if you do pageGlobal = new PageGlobal(); it doesn't crash.

Change it to this:

<div class="top-row h3">
    @if(pageGlobal != null)
    {
        pageGlobal.Title
    }
</div>

Or if you want a one liner:

<div class="top-row h3">
    @pageGlobal?.Title
</div>

Upvotes: 10

Ryan
Ryan

Reputation: 20139

It is not recommended to use Task.Run when you're doing Async programming. Try to use Task.FromResult in GetPageGlobalAsync instead of Task.Run

 public async Task<PageGlobal> GetPageGlobalAsync()
    {
        return await Task.FromResult( new PageGlobal());
    }

Upvotes: 1

Related Questions