简体   繁体   中英

Blazor: name does not exist in current context

I am receiving an error of CS0103 - 'The name 'newHotel' does not exist in the current context':

I've created a class called 'Hotel', and a property called 'HotelName'.
I've created a variable called 'newHotel', which is of type Hotel.
And I have initialised the variable with a value of "Paradise Beach".

@page "/hotels"


<h3>Hotels</h3>
<p>
    Hotel Name: @newHotel.HotelName // **THIS IS WHERE THE ERROR IS SHOWN IN VS2019**
</p>

Remaining code:

@code {

    protected override void OnInitialized()
    {
        base.OnInitialized();

        Hotel newHotel = new Hotel 
        {
            HotelName = "Paradise Beach"
        };
    }

    class Hotel
    {
        public string HotelName { get; set; }
    }
}

I can't tell where I am going wrong?

Many thanks,

It is because newHotel is a local variable declared in the OnInit method so it is out of scope. Add a property above the OnInitialized method for newHotel.


@code {

    ///Added property
    Hotel newHotel { get; set; } = new Hotel();

    protected override void OnInitialized()
    {
        base.OnInitialized();

        newHotel = new Hotel 
        {
            HotelName = "Paradise Beach"
        };
    }

    class Hotel
    {
        public string HotelName { get; set; }
    }
}

Edit: The next issue you will encounter is a NullReference error for newHotel due to the page trying to render before the OnInit method runs and newHotel is initialized. One option is to add a null check for newHotel another option is to initialize it when it is being declared.


@page "/hotels"


<h3>Hotels</h3>

@if(newHotel != null)
{
<p>
    Hotel Name: @newHotel.HotelName
</p>
}

I don't know if this has been resolved or not. For me, deleting the '.vs' folder did the trick. I don't actually think it's something in the code. It might be that Visual Studio acts up after updating to new versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM