Live Chat Icon For mobile
Live Chat Icon

Blazor FAQ

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

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, 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].

Please find the sample below.

[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]

<script src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=api_key' type='text/javascript'></script>
@page "/bingmaps"
@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); 
  }
     }

}

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]

….
<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;
    });
}

You can download the reference sample here.

Permalink

First to access browser seesionStorage in Blazor apps, write a custom code or use a third party package. The accessed data can be stored in the localStorage and sessionStorage.  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 the 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.

[startup.cs]
using Blazored.SessionStorage;

public void ConfigureServices(IServiceCollection services)
{
         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();
    }
}

Reference link: https://github.com/blazored/SessionStorage

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.

[startup.cs]

public void ConfigureServices(IServiceCollection services)
{
         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/

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/_Host.cshtml for Server Blazor app or ~/wwwroot/index.html for Blazor WebAssembly app.

[_Host.cshtml/index.html]

<head>
    <script src="~/script.js"></script>
    <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.

You can download the reference sample here.

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.

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

Share on twitter
Share on facebook
Share on linkedin

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

Please submit your question and answer.