Search code examples
c#razorblazorblazor-webassembly

Why a Blazor WebAssembly @foreach{} can't render a list?


I can't figure out why this list rendering isn't working no more throwing a weird exception:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Nullable object must have a value. System.InvalidOperationException: Nullable object must have a value. at System.Nullable`1[T].get_Value () <0x28f3be8 + 0x0000a> in :0 at .Client.Components.Threads.BuildRenderTree (Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) [0x010c7] in C:\Users\vOId\Desktop\projects<redacted><redacted>\Client\Components\Threads.razor:106 at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0 (Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) <0x2d39550 + 0x0001a> in :0 at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) <0x2d38ea8 + 0x00062> in :0 at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) <0x2d388a8 + 0x0004c> in :0 at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue () <0x2d35ce8 + 0x00098> in :0

The initialization of the list is usual, got the data from the server e add it to the list to render(ViewThreads):

protected async override Task OnInitializedAsync()
{
    var result = await ThreadService.GetThreads();
    if (result.IsValid)
        ViewThreads.AddRange((List<ViewThread>)result.Data);
    //...
}

Meanwhile at the rendering point at the first instruction of @foreach, line 106 from the exception, this is the rendering

//...
@foreach (var thread in ViewThreads)
{
    <p class="button is-light is-rounded neoFile petite-caps mb-3 @(CurrentThread != null && CurrentThread.Id == thread.Id ? "isSelected" : null)"
            @onclick="() => SelectThread(thread)" @key="thread">
        @thread.Title
    </p>
}
//...

This parts of code didn't change, it's just that suddenly the rendering of that list is throwing that exception and the elements are no longer rendered.

What it could be? Did anyone have a similar issue?


Solution

  • Nullable object must have a value.

    The code you posted here wil not produce that error. As you stated yourself, "This parts of code didn't change"

    So it is on some part you replaced with .... Look for a nullable property.

    And "suddenly the rendering of that list is throwing" is most likely caused by the data. Some column sneaked in with a null where you didn't expect it.