1

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?

Sergey Pitenko
  • 323
  • 1
  • 6
  • 13
  • 1
    Do not post code as images, that doesn't google well. – H H Nov 25 '19 at 19:50
  • Possible duplicate of [Blazor problem rendering data returned from Web Api](https://stackoverflow.com/questions/56289870/blazor-problem-rendering-data-returned-from-web-api) – H H Nov 25 '19 at 19:52

2 Answers2

9

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>
Gerrit
  • 804
  • 6
  • 18
  • You are right. Hmm, this error is really confusing. Interesting, on the other page the similar error is understandable "NullReferenceException: Object reference not set to an instance of an object. Site.Shared.NavMenu.BuildRenderTree(RenderTreeBuilder __builder) in NavMenu.razor @foreach (var service in pageGlobal.Person.Services)" – Sergey Pitenko Nov 26 '19 at 18:38
  • Adding this condition check actually helped me load the page. I still don't understand why it doen't work even if I have data. It gives error even before trying to render when I add a loop on the page . If I remove loop, loading data in varible takes place. – user1744582 Aug 18 '23 at 15:28
1

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());
    }
Ryan
  • 19,118
  • 10
  • 37
  • 53