Blazor FAQ - Lifecycle

Find answers for the most frequently asked questions
Expand All Collapse All

In a Blazor Server app, the default RenderMode is Server Prerendered. When the component is rendering with the ServerPrerendered render mode, the component is initially rendering statically as part of the page. 

On executing the first time, it is rendered as an MVC component directly when the page is requested and handled by “_Host” which is specified in “_Host.cshtml”. 

<body> 
    <component type="typeof(App)" render-mode="ServerPrerendered" /> 
    ……. 
</body>

Then the resources are loaded with the blazor.server.js script and start rendering a second time. Then the Razor pages are loaded as a Blazor component.
Note: If you are changing the RenderMode to Server, the lifecycle method executes only once.

[Pages/_Host.cshtml] 

<body> 
    <component type="typeof(App)" render-mode="Server" /> 
    ……. 
</body> 

Refer to this link for details. 

Permalink

Browser history can be accessed in Blazor using the window’s popstate event, which is fired when the user navigates the session history. We use the history API to get the history changes in the browser, and we can manually move to a specific page using back(), forward(), go().
When routing takes place in the application or browser, you can use the following code to store the current location:

Window.history.pushState({ prevUrl: window.location.href }, null, newpath)

To retrieve the previous URL, use the following code in your new route:

Window.history.state.prevUrl

Refer to this link for more information about the popstate event.
Refer to this link for more information about the history API.

View Sample in GitHub

Permalink

As opposed to how session cookies work, when opening a page in a new tab or window, a new session occurs with the browsing context. To access the browser sessionStorage in Blazor apps, write custom

code or use a third-party package. The accessed data can be stored in localStorage and sessionStorage. Know that localStorage is scoped to the user’s browser. If the user reloads the page or closes and reopens the browser, the state persists. Session storage is similar to local storage, but data in the session storage will be cleared after the session.

Install the Blazored.SessionStorage Nuget package in the NuGet package manager to store the session data in Blazor. Add the Blazored SessionStorage configuration to the WebAssembly app.

[Program.cs]

using Blazored.SessionStorage; 

. . . 
. . . 

            . . . 
            . . . 

            builder.Services.AddBlazoredSessionStorage(); 

[Index.razor]

@page "/" 

@inject Blazored.SessionStorage.ISessionStorageService sessionStorage 

<h2>@Name</h2> 

<button class="btn btn-primary" @onclick="Clear">Clear Session</button> 

@code { 
    public string Name; 
    protected override async Task OnInitializedAsync () 
    { 
        await sessionStorage.SetItemAsync("ID", "20019"); 
        await sessionStorage.SetItemAsync("Name", "John Smith"); 
        Name = "ID: " + await sessionStorage.GetItemAsync<string>("ID") + "Name : " + await sessionStorage.GetItemAsync<string>("Name"); 
    } 
    public async void Clear () 
    { 
        //this will clear the session data 
        await sessionStorage.ClearAsync(); 
    } 
} 
Permalink

You can add smooth scrolling to a Blazor app using a combination of Blazor components and JavaScript interop, similar to the functionality available in jQuery UI components.  

Step 1: Create a New Blazor App Run the following command to create a new Blazor WebAssembly app:  

.NET CLI  

dotnet new blazorserver -n SmoothScrollDemo 

Step 2: Add CSS Styles Open the wwwroot/css/site.css file and add the following CSS class for smooth scrolling: 

[wwwroot/css/site.css] 
 

.smooth-scroll { 

    scroll-behavior: smooth; 

} 

Step 3: Create a SmoothScroll Component Create a new Blazor component named SmoothScroll.razor

 [SmoothScroll.razor]

<!-- Pages/SmoothScroll.razor --> 
@page "/Smoothscroll" 
@inject IJSRuntime JSRuntime 

<h3>Smooth Scrolling Example</h3>  

<div class="smooth-scroll"> 
    <p> 
        This is a demonstration of smooth scrolling in a Blazor app. 
        Click the button below to smoothly scroll to the bottom of the page. 
    </p> 
    <button @onclick="ScrollToBottom">Scroll to Bottom</button> 
</div> 
<div class="content"> 
    <!-- Add some content here to make the page longer --> 
    <h4>Smooth Scrolling in Blazor: Elevating User Experience with Elegance</h4> 
    <p>In the realm of modern web development, the user experience reigns supreme, and every nuance plays a pivotal role in crafting an immersive and delightful interaction. One such understated yet highly impactful element is the art of smooth scrolling. Blazor, the cutting-edge web framework by Microsoft, empowers developers with the ability to seamlessly integrate this feature into HTML elements. By adding an enchanting fluidity to the scrolling mechanism, Blazor transforms the user journey into an elegant dance, enhancing engagement and delivering a heightened sense of sophistication.</p> 
    <h4>The Essence of Smooth Scrolling</h4> 
    <p>Smooth scrolling, at its core, is the art of imbuing scrolling actions with an exquisite gracefulness. Unlike the conventional abrupt and jarring movements that characterize traditional scrolling, smooth scrolling introduces a harmonious glide that seamlessly navigates users through various sections or elements on a web page. This simple yet transformative touch has the power to transcend the mundane, transforming user interactions into a symphony of motion and elegance.</p> 
    <h4>Unveiling the Benefits</h4>  
    <ol> 
        <li> 
            <h6>Enhanced User Engagement:</h6> 
            By eliminating the disorienting jumps, smooth scrolling creates a captivating rhythm that keeps users immersed and engaged as they explore the content. 
        </li> 
        <li> 
            <h6>Visual Fluidity:</h6> 
             The graceful transitions between sections establish a visual continuity that feels natural and intuitive, amplifying the overall aesthetics of the website. 
        </li> 
        <li> 
            <h6>Improved Readability:</h6> 
             For lengthy articles or content-rich pages, smooth scrolling guarantees a comfortable reading experience by gradually revealing the content. 
        </li> 
        <li> 
            <h6>  Subtle Sophistication: </h6> 
          Smooth scrolling lends an air of refinement to the user journey, elevating the perception of the website's design and enhancing its overall brand image. 
        </li> 
        <li> 
            <h6>Extended Time on Page:</h6> 
             The fluidity and beauty of smooth scrolling entice users to linger, thereby increasing their time spent on the website and fostering a deeper connection. 
        </li> 
    </ol> 
</div> 

@code { 
    private async Task ScrollToBottom() 
    { 
        await JSRuntime.InvokeVoidAsync("scrollToBottom"); 
    } 
} 

Step 4: Add the following JavaScript function for scrolling to the bottom of the page in _Host.cshtml. 

[_Host.cshtml]

<body> 
……. 
    <script src="_framework/blazor.server.js"></script> 
    <script> 
        window.scrollToBottom = function () { 
            window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }); 
        }; 
    </script> 
</body> 

Step 5: Test the Smooth Scrolling Effect Run the Blazor app using the following command: 
NET CLI

dotnet run 

View Sample in GitHub  

Permalink

To set the active value on a select dropdown control, you must bind a property to the value in the select component and change that bind property in the event call

@page "/dropdown"


<select class="form-control" value="@listdefault" @onchange="@OnSelect" style="width:150px">
    @foreach (var template in templates)
    {
<option value=@template>@template</option>
     }
</select>

<h5>@selectedString</h5>
<select class="form-control" value="@citydefault" @onchange="@OnSelectCity" style="width:150px">
       @foreach (var template in citytemplates)
        {
   <option value=@template>@template</option>
}
</select>
<h5>@selectedCity</h5>
<button class="btn btn-primary" @onclick="@Change">Change</button>

@code {
    List<string> templates = new List<string>() { "America", "China", "India", "Russia", "England" };
    List<string> citytemplates = new List<string>();
    List<string> usa = new List<string>() { "Los-Angeles", "Florida", "Newyork", "Washington", "California" };
    List<string> china = new List<string>() { "Wuhan", "Beijing", "Shanghai", "Macau", "Taipei " };
    List<string> india = new List<string>() { "New-Delhi", "Mumbai", "Chennai", "Bangalore", "Hyderabad" };
    List<string> russia = new List<string>() { "Moscow", "Saint Petersburg", "Novosibirsk", "Yekaterinburg", "Kazan" };
    List<string> england = new List<string>() { "Birmingham", "Cambridge", "Manchester", "Leicester", "London" };
    string selectedString = "";
    string selectedCity = "";
    string listdefault = "India";
    string citydefault = "Mumbai";
    void OnSelect(ChangeEventArgs e)
    {
        if (e.Value.ToString() == "America")
        {
            citytemplates = usa;
        }
        else if (e.Value.ToString() == "China")
        {
            citytemplates = china;
        }
        else if (e.Value.ToString() == "India")
        {
            citytemplates = india;
        }
        else if (e.Value.ToString() == "Russia")
        {
            citytemplates = russia;
        }
        else
        {
            citytemplates = england;
        }
        selectedString = "Selected Country is: " + e.Value.ToString();

        StateHasChanged();
        Console.WriteLine("It is definitely: " + selectedString);
    }
    void OnSelectCity(ChangeEventArgs e)
    {
        selectedCity = "Selected CIty is: " + e.Value.ToString();
        Console.WriteLine("It is definitely: " + selectedString);
    }
    void Change(MouseEventArgs args)
    {
        listdefault = "Russia";
    }
    protected override void OnInitialized()
    {
        citytemplates = india;
        citydefault = "Chennai";
        base.OnInitialized();
    }
}

In the above sample, the city dropdown is changed based on the country selected in the country dropdown.

Permalink

To add Bing Maps to a Blazor application follow the steps.

  • Include the Bing Maps Web API scripts in the index.html/_Host.cshtml/_Layout.cshtml, This is used to retrieve the Bing Maps-related information by sending a request to the Bing Maps server and loading the same to the Blazor application. 
  • Initialize maps in a Blazor application by using a JavaScript interop in the razor file [index.razor].

[Script.js]

function loadBingMap() { 
    var map = new Microsoft.Maps.Map(document.getElementById('map'), {}); 
    var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), null); 
    map.entities.push(pushpin); 
    return ""; 
} 

[index.html/_Host.cshtml/_Layout.cshtml]

<script src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=api_key' type='text/javascript'></script> 

[Razor file] 

@page "/" 
@inject IJSRuntime JSRuntime 
<h1>Display Bing Map</h1> 
<div id="map" style="height:500px;width:100%;"> </div> 
@code { 
    protected override async Task OnAfterRenderAsync ( bool firstRender ) 
    { 
        if (firstRender) 
        { 
            await JSRuntime.InvokeVoidAsync("loadBingMap", null); 
        } 
    } 
}

View Sample in GitHub

Permalink

To use jQuery UI components in a Blazor application follow the steps:

  • Reference the source scripts for jQuery and its UI components.
  • Create the elements required for rendering jQuery UI components in the razor page [index.razor].
  • Initialize the jQuery components in the OnAfterRender lifecycle method in your Blazor application by using the JavaScript Interop’s InvokeVoidAsync method.

Refer to the following code sample.

[_Host.cshtml/_Layout.cshtml/index.html] 

….
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="~/script.js"></script>
….

[index.razor]

@page "/"
@inject IJSRuntime jsRuntime

<h1>jQuery UI Components in Blazor</h1>

<br />

<h2>jQuery Accordion Component</h2>

<br />

<div id="accordion">
    <h3>ASP.NET</h3>
    <div>
        <p>
            Microsoft ASP.NET is a set of technologies in the Microsoft .NET Framework for building Web applications and XML Web services.
            ASP.NET pages execute on the server and generate markup such as HTML, WML, or XML that is sent to a desktop or mobile browser.
            ASP.NET pages use a compiled,event-driven programming model that improves performance and enables the separation of application logic and user interface.
        </p>
    </div>
    <h3>ASP.NET MVC</h3>
    <div>
        <p>
            The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller.
            The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications.
            The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication.
        </p>
    </div>
    <h3>JavaScript</h3>
    <div>
        <p>
            JavaScript (JS) is an interpreted computer programming language.
            It was originally implemented as part of web browsers so that client-side scripts could interact with the user, control the browser, communicate asynchronously, and alter the document content that was displayed.
            More recently, however, it has become common in both game development and the creation of desktop applications.
        </p>
    </div>
</div>

<br />

<div class="jquery-btn">
    <button>Click Me</button>
</div>

<br />

<p>Clicked: <span class="click-count">0</span></p>

<br />

@code {
    protected override async void OnAfterRenderAsync(bool firstRender)
    {
        await jsRuntime.InvokeVoidAsync("renderjQueryComponents");
        await base.OnAfterRenderAsync(firstRender);
    }
}

[script.js]

var clickCount = 0;

function renderjQueryComponents() {
    $("#accordion").accordion();
    $(".jquery-btn button").button();
    $(".jquery-btn button").click(function () {
        console.log('Clicked');
        $('.click-count')[0].innerText = ++clickCount;
    });
}

View Sample in GitHub

Permalink

First to access browser Session Storage in Blazor apps, write a custom code or use a third party package. The accessed data can be stored in the Local Storage and Session Storage.  The Local Storage is scoped to the user’s browser. If the user reloads the page or closes and reopens the browser, the state persists. Session storage is similar to Local Storage but the data in the session storage will be cleared after the session. 

Use the Blazored.SessionStorage package to store the session data in Blazor. For this install the package and add the service to the application.

[Program.cs] 

using Blazored.SessionStorage; 
…
builder.Services.AddBlazoredSessionStorage();

[index.razor]

@page "/"
@inject Blazored.SessionStorage.ISessionStorageService sessionStorage

<h2>@Name</h2>
<button @onclick="Clear">Clear Session</button>
@code {
    public string Name;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await sessionStorage.SetItemAsync("ID", "20019");
        await sessionStorage.SetItemAsync("Name", "John Smith");
        Name = "ID: " + await sessionStorage.GetItemAsync<string>("ID") + "Name : " + await sessionStorage.GetItemAsync<string>("Name");
    }
   public async void Clear()
   { 
    //this will clear the session data 
     await sessionStorage.ClearAsync();
    }
}
Permalink

To access browser  localStorage in Blazor apps, write a custom code or use a third party package. The difference between localStorage and sessionStorage  is: The localStorage is scoped to the user’s browser. If the user reloads the page or closes and reopens the browser, the state persists. Session storage is similar to local storage but the data in the session storage will be cleared after the session.

The  Blazored.LocalStorage package can be used to access the browser’s local storage in Blazor. For this you need to install the package and add the service to the application.

[Program.cs]

using Blazored.LocalStorage; 
…
builder.Services.AddBlazoredLocalStorage(); 

[index.razor]

@page "/" 
@inject Blazored.LocalStorage.ILocalStorageService localStorage 
<h2>@Name</h2> 
<button @onclick="Clear">Clear LocalStorage</button> 

@code { 
    public string? Name; 
    protected override async Task OnAfterRenderAsync ( bool firstRender ) 
    { 
        await localStorage.SetItemAsync("ID", "20019"); 
        await localStorage.SetItemAsync("Name", "John Smith"); 
        Name = "ID: " + await localStorage.GetItemAsync<string>("ID") + "Name : " + await localStorage.GetItemAsync<string>("Name"); 
    } 
    public async void Clear () 
    { 
        //this will clear the local storage 
        await localStorage.ClearAsync(); 
    } 
} 

To access the local storage using the OnInitialized method, disable the ServerPrerender in _Host.cshtml. 

Reference link: https://chrissainty.com/blazored-local-storage-v0-3-0-released/ 

View Sample in GitHub

Permalink

To add Google Maps to a Blazor application, use the Google Maps API script. To initialize Google Maps in Blazor we need to use a JavaScript interop. 

Add the following scripts to ~/Pages/_Layout.cshtml /_Host.cshtml for Server Blazor app or ~/wwwroot/index.html for Blazor WebAssembly app. 

[_Host.cshtml/_Layout.cshtml/index.html] 

<head> 
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script> 
</head> 

[Script.js]

function initialize() { 
    var latlng = new google.maps.LatLng(40.716948, -74.003563); 
    var options = { 
        zoom: 14, center: latlng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    var map = new google.maps.Map(document.getElementById("map"), options); 
} 

[index.razor]

@page "/" 
@inject IJSRuntime JSRuntime 

<h1>Display Google Map</h1> 
<div id="map" style="height:500px;width:100%;"> 
</div> 

@code { 
    protected override async Task OnAfterRenderAsync ( bool firstRender ) 
    { 
        if (firstRender) 
        { 
            await JSRuntime.InvokeVoidAsync("initialize", null); 
        } 
    } 
}

In the above example, Google Maps is initialized in the OnAfterRenderAsync life cycle method. By invoking it using a JavaScript interop, this will initialize Google Map API when the page is rendered. 

View Sample in GitHub 

Note: If you’d like to know how to render Google Maps in Syncfusion Blazor Map, take a look at our  documentation section

Permalink

The lifecycle methods OnAfterRenderAsync and OnAfterRender are called only when a component has finished rendering. The element and component references are populated at this point. By using these methods, the user can activate third-party JavaScript libraries that operate based on the DOM elements. 

Razor file 

@page "/" 
<input type="text" @bind="@message" /> 

@code{ 
    private string? message { get; set; } 
    protected override async Task OnAfterRenderAsync ( bool firstRender ) 
    { 
        // Perform any asynchronous operations after the component has been rendered 
        if (firstRender) 
        { 
            message = "Component rendering finished"; 
            await Task.Yield(); // Ensure the UI rendering is complete 
            StateHasChanged(); // Trigger UI update 
        } 
    } 

    protected override void OnAfterRender ( bool firstRender ) 
    { 
        // Perform any synchronous operations after the component has been rendered 
        Console.WriteLine("Component rendering completed"); 
        base.OnAfterRender(firstRender); 
    } 
} 
Permalink

Blazor provides both synchronous and asynchronous initialization lifecycle methods to perform additional operations on components during initialization and rendering. Initialization methods are:

  • OnInitialized:  Override this method in components for synchronous operations. 
  • OnInitializedAsync:  Override this method in components for asynchronous operations.

    OnInitialized and OnInitializedAsync are executed when the component is initialized after having received its initial parameters from its parent component in the render tree. 

    Use OnInitializedAsync when the component performs an asynchronous operation and the changes should refresh the component when the operation is completed.

    Refer to this link for more details. 

    Permalink

    There are around seven lifecycle methods available in Blazor, which provides synchronous as well as asynchronous lifecycle methods.

    OnInitialized ()

    This is the synchronous method executed when the component is initialized.

    OnInitializedAsync()

    This is the asynchronous method executed when the component is initialized.

    OnParametersSet()

    This is the synchronous method when the component has received the parameter from parent component.

    OnParametersSetAsync()

    This is an asynchronous method when the component has received the parameter from the parent component.

    ShouldRender()

    This method is used to suppress the refreshing of the UI. If this method returns true, then the UI is refreshed. Otherwise, changes are not sent to the UI. It always does the initial rendering despite its return value.

    OnAfterRender(bool firstRender)

    This is the synchronous method executed when the rendering of all the references to the component are populated.[JB1] 

    OnAfterRenderAsync(bool firstRender)

    This is the asynchronous method which is executed when the rendering of all the references to the component are populated.

    @page "/lifecycle"
    <h1>Life cycle Methods ..</h1>
    @foreach (var item in EventType)
    {@item <hr />}
    @code {
    
        List<string> EventType = new List<string>();
        protected override void OnInitialized()
        {
            EventType.Add(" 1 OnInit");
        }
        protected override async Task OnInitializedAsync()
        {
            EventType.Add("2 OnInit Async");
            await Task.Delay(1000);
        }
        protected override void OnParametersSet()
        {
            EventType.Add("3 On Parameter set ");
        }
        protected override async Task OnParametersSetAsync()
        {
            EventType.Add(" 4 OnParametersSet Async Started");
            await Task.Delay(1000);
        }
        protected override bool ShouldRender()
        {
            EventType.Add(" 5 Should render called");
            return true;
        }
        protected override void OnAfterRender(bool firstRender)
        {
            EventType.Add(" 6 OnAfterRenderStarted");
        }
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            EventType.Add(" 7 OnAfterRender Async Started");
            await Task.Delay(1000);
        }
    }
    

     Reference link:

    https://docs.microsoft.com/en-us/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1

    Permalink

    Share with

    Couldn't find the FAQs you're looking for?

    Please submit your question and answer.