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”.
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.
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:
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.
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.
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
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 "";
}
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.
@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;
});
}
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();
}
}
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();
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);
}
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.
To force a component to rerender, use the “StateHasChanged” method in Blazor, to notify that the state has been changed and requires re-rendering. For more information on the same, check this link.
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);
}
}
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.
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.