Useful things about Blazor, I wish I knew at the start

Helpful or interesting things, that I wish I have had known when starting working blazor (server).

Kim
8 min readJun 11, 2023
Photo by Turag Photography on Unsplash

I’m not an industry expert or something but I worked with blazor (server) for over a year now and every time I discover something new or helpful. So, I decided to create a post about it, to help someone, maybe this post helps someone, fix a certain problem, or bring up new ideas.

These things are obviously no secrets or hidden things but rather things that would have saved me time, when I would have found an article like this when I started, so it feels like a message to my prior self.

To clarify again, this is about blazor server, certain things like asynchronous tasks are not transferable to webassembly, so before using them with wasm, inform yourself about the usage.

This post is about:

  • The use of InvokeAsync and StateHasChanged
  • Implementation of Local- and SessionStorage
  • Usage of frameworks
  • AddTransient(), AddScoped() and AddSingleton()
  • The rendermodes: ServerPrerendered, Static and Server
  • Rendering HTML out of anything (MarkupString)
  • How to deploy and use certificates with blazor server

Use InvokeAsync(), when using StateHasChanged()

When updating the UI, say like after grabbing data of a database or performing a calculation, you want to display the result. The UI is already loaded (most of the times), so you need to tell blazor to update it, that’s done using StateHasChanged(), it forces blazor to refresh certain UI (the caller component), to update its displayed content.

So, what do I mean with InvokeAsync() ? InvokeAsync forces blazor to execute the code inside of it, to be performed on the main-thread, to update UI you must be on the main-thread (or the certain UI-thread).

Normally blazor does StateHasChanged behind the hood for you, like when pressing a button and updating a timer or something, but sometimes it is not, e.g.:

  • when working with asynchronous tasks, no matter the task or thread you are in, if it is not the main thread you need to use InvokeAsync.
  • if using a timer or callback which awaited an execution asynchronously.

The example from blazor-university is a pretty good, we start a timer inside the OnInitialized(), therefore we need to call InvokeAsync(), to call StateHasChanged successfully, without it the call to update the UI would not work correctly.

protected override void OnInitialized()
{
base.OnInitialized();
Timer = new Timer(_ =>
{
InvokeAsync(StateHasChanged);
}, null, 500, 500);
}

Good examples are from Microsoft and blazor-university, to read here:

You can use LocalStorage and SessionStorage to store things (for the user)

I was at a point where I wanted to create some kind of login or authentication by myself, don’t judge me you have to fall before you can learn. To do this, I did something rather strange, I used a “Manager” class, which contained a bool IsLoggedIn, so I checked the password in the database and set the bool, little did I knew that everybody that wanted to access the secret-login-secured-page could now do it because I didn’t use correct dependency injection approach.

Snapped from: https://i.imgflip.com/51ugwm.png
Snapped from: https://i.imgflip.com/51ugwm.png

Before Microsoft enabled the usage of LocalStorage and SessionStorage in blazor you had to use nuget-packages like “LocalStorage” created by “Blazored”, these still can be used and are more customizable, but I rather use the .net implementation.

Local- and SessionStorage can be used to store data for a certain time inside the browsers storage, the data inside those is encrypted and decrypted when accessing them, so nobody should be able to do something to them, if they get manipulated and you try to read the value, the just don’t work anymore as they are no longer correctly decryptable 😊 so this is a safe approach but I wouldn’t store passwords or something serious inside of those.

What is the difference you may ask yourself now, why are there two Storage-types? That’s a good point, see LocalStorage stores the data until it is deleted by you or the user, even closing the browser or opening new tabs the data is there and will be available to all tabs in the same browser. Using SessionStorage tho, the data is only available in this on browser-tab and closing the browser eliminates this data.

There is a good chapter in the Microsoft docs for this too: https://learn.microsoft.com/de-de/aspnet/core/blazor/state-management?view=aspnetcore-7.0&pivots=server#browser-storage-server

To access the Storage-types, you must either inject ProtectedLocalStorage or ProtectedSessionStorage in the component you want it to use, depending on what you want to use or if you want both, inject both obviously.

To access the data, use following code, as you can see the ProtectedBrowserStorageResult can be checked using .Success, if that is wrong, I wouldn’t access .Value since the data is corrupt or non-existing.

ProtectedBrowserStorageResult<T> Object2Acess = await SessionStore.GetAsync<T>("object2access");

if (Object2Acess.Success) {
Console.WriteLine(Object2Acess.Value);
}

To set data you use: await PrefStore.SetAsync("object2access", "string to set in storage"/or object);

And to delete: await PrefStore.DeleteAsync("object2access");

Use Frameworks

At the beginning of my blazor-journey, I didn’t use any frameworks, to think about this now is scaring me, those frameworks often help a lot when it comes to design or functionality implementation. There are a lot of frameworks or libraries that can help you, I’m not advertising for MudBlazor, but I love using it, I also tried Blazorise and Radzen too they are also very good but personally I have an easier start when using MudBlazor.

I cut myself short in this chapter, I don’t have that much to say, I just want to show one or two things to give you an idea why to use frameworks rather than doing everything by yourself.

For example, see the “snackbar” (https://mudblazor.com/components/snackbar#usage), with it you can display messages that pop-up it’s a great way to draw attention or notify the user about something, implementing this yourself means to get into JavaScript, Blazor is here to avoid using javascript but of course if you like it and are good at it that’s no point for you, I guess 😉

https://mudblazor.com/components/snackbar#usage

The second thing is the “dropzone” (https://mudblazor.com/components/dropzone#basic-usage), implementing this allows dragging and dropping elements on your page, it’s good to create a calendar or something.

Is work in blazor and javascript but if you don’t know any javascript, this would be impossible without libraries, because Microsoft doesn’t want to implement this on their own: https://visualstudiomagazine.com/articles/2022/03/30/blazor-drag-drop.aspx

https://mudblazor.com/components/dropzone#basic-usage

For more on this, see: https://jonhilton.net/blazor-component-libraries he names and describes a few, also paid ones so for those working in enterprise, you find customer support too.

Learn the power of AddTransient(), AddScoped() and AddSingleton()

If you create your own services and I guess you do because you most likely use a database and that is enough, you read something about those three Add..(). They are a part of the Dependency Injection (DI). So, you need to understand when to use which to use your services the right way.

  • AddTransient() — The service is created for every request.
  • AddScoped() — The service is created once for every request.
  • AddSingleton() — The service is created once and the same is used for everybody (dangerous if you store important states or passwords).

To understand the right usage, I suggest reading a whole article about it, they are understood pretty fast because this is only a tiny fraction of DI, but it is important since the wrong usage can bring you headache or problems (especially if you don’t understand them).

Easy to understand are following articles:

Differentiate the Rendermodes ServerPrerendered, Static and Server

This fine piece of text controls the render-mode, as it’s also the name. I’m trying to explain it as best and easy as I can, tho I still recommend reading something detailed to understand the benefits and drawbacks of it thorough.

RenderMode.Server:

  • In this mode, all UI rendering is performed on the server.
  • In Blazor Server, when an event happens on the client-side, it’s sent to the server for UI updates. The server sends back updated HTML, and the client-side JavaScript handles user interactions and UI updates.

RenderMode.ServerPrerendered:

  • In this mode, the initial rendering of the UI is performed on the server, like the RenderMode.Server mode.
  • After the initial rendering, subsequent rendering is handled on the client-side by JavaScript. This improves user experience by reducing round trips to the server, lowering latency, and enhancing interactivity.

RenderMode.Static:

  • This generates static HTML that contains everything, dynamic updates or changes like in prerendered, or server are not possible.

With .net 7+ it’s located only in the _Host.cshtml file of your project, before there were two occurrences, also in the _Layout.cshtml file.

Content of _Host.cshtml

You can render a string to html using (MarkupString)

You can easily render HTML that is inside a variable or something, you just must put (MarkupString) in front of it, so the engine knows, this must be rendered and not displayed as plain text.

This gives a lot of cool possibilities, like a very easy live-html editor with view where the user can input HTML on one side and the other half (split-view), displays the rendered HTML. I used it in a project myself, to enable a more custom experience by letting the users type in the HTML, putting it inside a database and when querying it just using (MarkupString) to bring it to live.

If you need more informations, see syncfusion’s short post: https://www.syncfusion.com/faq/how-do-i-render-raw-html-in-blazor

How (to enable https,) to deploy blazor server to the real world

I don’t want to spend too much text on this one, since I wrote a bit about it, but I didn’t knew how to deploy a blazor server app with domain and certificate until I found out about LettuceEncrypt, so if you want to create something like this URL shortener I created (removed) then check this post out.

More to come with .net 8

With the release of .net 8 there are new features also for blazor, I don’t include them here, I want to end this article with this chapter and encourage you to read about those changes since they are pretty interesting:

Thank you for reading, I hope one or two things helped you as they helped me when I found out about them.

--

--

Kim

I'm trying to write about things people might need or with which I struggled, to help others. https://kmliebl.de