Live Chat Icon For mobile
Live Chat Icon

Blazor FAQ

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

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

While making an API call, create and run an asynchronous task with the Run method to notify the wait using a spinner. The completion of the task can be notified using the  CompletedTask property.

[index.razor]

@page "/"

<style>
    .loader {
        border: 5px solid #f3f3f3;
        border-radius: 50%;
        border-top: 5px solid #f58205;
        width: 30px;
        height: 30px;
        -webkit-animation: spin 2s linear infinite; /* Safari */
        animation: spin 2s linear infinite;
    }
    /* Safari */
    @@-webkit-keyframes spin {
        0% {
            -webkit-transform: rotate(0deg);
        }
        100% {
            -webkit-transform: rotate(360deg);
        }
    }
    @@keyframes spin {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
</style>

<h1>Counter</h1>

<p>
    Current count: <div class="@(spin ? "loader" : "")"> @(spin?"":currentCount.ToString()) </div>
</p>

<button class="btn btn-primary" @onclick="@IncrementCount"> Click me </button>
<button class="btn btn-dark" @onclick="@AsyncCallBack"> API Call Back </button>

@code {
    int currentCount = 0;
    bool spin = false;
    void IncrementCount()
    {
        currentCount++;
    }

    async Task AsyncCallBack()
    {
        spin = true;
        await Task.Run(() => APICallBack());  //<==check this!!!
        currentCount++;
        spin = false;
        await Task.CompletedTask;
    }

    void APICallBack() => Task.Delay(1500).Wait();
}

Output:

Permalink

An HTTP Delete request can be sent to delete a resource from the API server using the DeleteAsync () method provided by the HttpClient class.

Razor

@page "/employee/delete"
@inject HttpClient Http
@inject NavigationManager Navigate
.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
    Employee emp = new Employee();
    protected async Task Delete()
    {
        await Http.DeleteAsync("api/Employee/Delete/" + Convert.ToInt32(empID));
        Navigate.NavigateTo("/employee");
    }
}

Web API

[HttpDelete]
[Route("api/Employee/Delete/{id}")]
public void Delete(int id)	
{
    employee.DeleteEmployee(id);
}

Reference link: https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

Permalink

An HTTP GET request can be sent to get a resource from the API server using the GetJsonAsync() method provided by the HttpClient class.

CSHTML

@page "/employee"
@inject HttpClient Http

.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
        Employee[] empList;

        protected override async Task OnInitializedAsync()
        {
            empList = await Http.GetJsonAsync<Employee[]>("/api/Employee/Index");
        }
}

Web API

[HttpGet]
[Route("api/Employee/Index")]
public IEnumerable<Employee> Index()
{
    return employee.GetAllEmployees();
}

Reference link: https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

Permalink

An HTTP POST request can be sent to add new data in the API server using the SendJsonAsync () method provided by the HttpClient class.

Razor

@page "/employee/add"
@inject HttpClient Http

.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
    Employee emp = new Employee();
    protected async Task CreateEmployee()
    {
        await Http.SendJsonAsync(HttpMethod.Post, "/api/Employee/Create", emp);
    }
}

Web API

[Route("api/Employee/Create")]
public void Create([FromBody] Employee employee)
{
    if (ModelState.IsValid)
        this.employee.AddEmployee(employee);
}

Reference link:

https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

Permalink

The HTTP PUT method is used to completely replace a resource on the API server. We can use the HttpClient to send a PUT request to an API server using the SendJsonAsync () method. 

CSHTML       

@page "/employee/edit"
@inject HttpClient Http

.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
    Employee emp = new Employee();
    protected async Task UpdateEmployee()
    {
        await Http.SendJsonAsync(HttpMethod.Put, "api/Employee/Edit", emp);
        UriHelper.NavigateTo("/employee");

    }
}

Web API

[HttpPut]
[Route("api/Employee/Edit")]
public void Edit([FromBody]Employee employee)
{
    if (ModelState.IsValid)
        this.employee.UpdateEmployee(employee);
}

Reference link:

https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

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.