Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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() };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading