Search code examples
labelrazor-pages

How to dynamically update a label in Razor c#


How to add code in OnInitializedAsync to update the label?

<div id="container">
    <label id="labelId" class="label"></label>
</div>

@code {
    protected override async Task OnInitializedAsync()
    {
        // code to set the display text for the label here
    }   
}

Solution

  • <div id="container">
        <label id="labelId" class="label">@_labelText</label>
    </div>
    
    @code {
        private string _labelText;
        
        protected override void OnInitialized()
        {
            _labelText = "This is a label.";
        }   
    }
    

    If you are not calling any async methods then you should use OnInitialized instead of OnInitializedAsync.