Blazor .NET 8 preview 7 rendering modes – Blazor

by
Maya Patel
.net-8.0 asp.net-core-8 aws-aurora-serverless blazor image-rendering

Quick Fix: To enable interactivity for individual components with Blazor Server in .NET 8 preview 7, use the @attribute [RenderModeServer(false)] directive. This allows you to selectively render specific components in client-side mode, while keeping the rest of the application server-rendered.

The Problem:

In Blazor component development using .NET 7, you were able to switch between two rendering modes: RenderMode.Server and RenderMode.ServerPrerendered. However, after upgrading to .NET 8, the ability to use RenderMode.Server seems to have disappeared. Now, removing the @attribute [RenderModeServer] makes the component static, while adding it results in the component being rendered twice, which is undesired. How can you achieve the behavior of RenderMode.Server (without the prerendering) in Blazor on .NET 8?

The Solutions:

Solution 1: Utilizing RenderModeServer attribute with false value

In Blazor on .NET 8, you can still choose between the two render modes: Server and ServerPrerendered, by using the RenderModeServer attribute. However, you need to set its value to false to achieve the behavior of RenderMode.Server. Here’s how you can do it:

Add the following attribute to the Blazor component where you want to enable server-side rendering without prerendering:

@attribute [RenderModeServer(false)]

With this attribute, you can now benefit from the following behavior:

  • The onInitialize method will be executed only once, just like in the RenderMode.Server mode in Blazor on .NET 7.
  • The component will be interactive, meaning the counter button will increase the value when clicked.
  • The component will not be rendered twice, unlike in the default RenderMode.ServerPrerendered mode.

This approach allows you to achieve the desired behavior of the RenderMode.Server mode in Blazor on .NET 8.

Q&A

How to set the RenderMode.Server in Blazor on .NET 8?

Try @attribute [RenderModeServer(false)].

With @attribute [RenderModeServer(false)], will onInitialize run once or twice?

onInitialize will run only once.

Video Explanation:

The following video, titled ".NET 8 Preview 7 - Auto Switch from Blazor Server to Web Assembly ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

With the latest preview version of .NET 8 (Preview 7), you now have the ability to have Web Assembly components render first on the server ...