Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable does not exist in the current context in Blazor component

I am building a Blazor (Blazor server) project in .NET 6 and I have come to a problem, in one component I can declare a variable, but when I try to do something with that variable immediately after I declare it, it "does not exist in the current context".

Resources.razor

@using Models

<div>
<h2>Resources</h2>

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>State</th>
        </tr>
    </thead>
    <tbody>
        @foreach (Resource resource in ResourceList)
        {
            <tr>
                <td>@resource.Name</td>
                <td>@resource.DisplayStatus</td>
            </tr>
         }
    </tbody>
</table>
</div>


@code {
    public List<Resource> ResourceList { get; set; }
    ResourceList = new List<Resource>(); // this line throws an error (IDE1007: the name 'ResourceList' does not exist in the current context)
    ResourceList.Add(new Resource()); // this one too
}

I have tried moving it to the new file Resources.razor.cs but it has the same problem. It is not working not just for List<Resource> but even for string or int. I have also tried to make a completely new razor component and try to rewrite it but it still does not work.

like image 246
Jan Matějíček Avatar asked Mar 12 '26 09:03

Jan Matějíček


1 Answers

Place the logic for initializing and assigning value in the OnInitialized{Async} method.

@code {
    public List<Resource> ResourceList { get; set; }

    protected override void OnInitialized()
    {
        ResourceList = new List<Resource>();
        ResourceList.Add(new Resource());
    }
}

Or you can directly initialize the ResourceList when it is declared.

@code {
    public List<Resource> ResourceList { get; set; } = new List<Resource>() { new Resource() };
}
like image 83
Yong Shun Avatar answered Mar 13 '26 23:03

Yong Shun