I'm getting the following error. From a simple all records call from my API.
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at MusicManager.Client.Pages.Themes.BuildRenderTree(RenderTreeBuilder __builder) in
E:\Projects\marklalich\MusicManager\MusicManager\Client\Pages\Themes.razor:line 7
at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder
batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
Here's the code, what am I doing wrong?
@page "/themes"
@inject IThemeService ThemeService
<div class="container mt-3">
<h2>Themes</h2>
<p>asfgasfgasdfgasdfg</p>
@if (ThemeService.Themes.Count == 0) <== this is the line the error is referencing
{
<span>Loading Themes...</span>
}
else
{
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
@foreach (var theme in ThemeService.Themes)
{
<tr>
<td>@theme.Title</td>
</tr>
}
</tbody>
</table>
}
</div>
@code {
protected override async Task OnInitializedAsync()
{
await ThemeService.GetThemes();
}
}
The component first renders when
await ThemeService.GetThemes();
yields.
At this point I'm guessing ThemeService.Themes
is null so there's no Themes to count:
@if (ThemeService.Themes.Count == 0)
So you need to make a null check:
@if (ThemeService.Themes is null)
Check the FetchData
page.