Updated: 19 January 2025
Notes
- Blazor is a Single Page Application framework that is part of the ASP.NET Core framework.
- Blazor supports both server and client side rendering.
- Blazor apps are built with reusable UI components which may be shared within or across applications.
- Client side – uses WebAssembly.
- Largely eliminates the need to write Javascript.
- Enables PWA development because of off-line WASM.
- Server side – uses ASP.NET Core and communicates with client via SignalR.
- Blazor apps are based on components. A component in Blazor is an element of UI, such as a page, dialog, or form.
- Blazor vs Razor
- Migrate from ASP.NET Core in .NET 7 to .NET 8
- WebAssembly is an open-source W3C standard supported by all major browsers.
- Components
- Components are .NET C# classes built into .NET assemblies
- Component parameters
- Component parameters pass data to components. They are defined using C# properties on the component class with the
[Parameter]
attribute.
Blazor Server vs Blazor Web vs Blazor WebAssembly
- Blazor Server (.NET 7 and below, also supported in .NET 8 without code changes). Renders the UI on the server. After page is loaded on client SignalR used for communication with server. Blazor Server apps run in a manner similar to ASP.NET MVC or Razor Pages apps.
- Blazor Web (.NET 8 and above)
- Blazor WebAssembly. Upon first loading both the application, its dependencies and .NET framework (as WASM) are downloaded to the client in parallel. The application then runs in a sandboxed .NET environment on the client.
Blazor project templates
New Blazor Server app
dotnet new blazorserver -o TodoList
New Blazor Web app
dotnet new blazor -o BlazorWebAppMovies
New Blazor WebAssembly app
dotnet new blazorwasm -o TodoList
Component code example
Components can be called using declarative syntax
<Message MessageText="hello" MessageStyle="alert"></Message>
File Message.razor holds the components source code
<p MessageStyle=@MessageStyle>@MessageText</p>
@code {
[Parameter]
public string? MessageText { get; set; }
[Parameter]
public string? MessageStyle { get; set; }
}
Lifecycle
OnInitialized
/OnInitializedAsync
- Use these events to fetch data and present the user interface.
OnParameterSet
/OnParameterSetAsync
- This event runs when the component has received all parameters. It executes every time the parameters are updated.
OnAfterRender
/OnAfterRenderdAsync
- Once the component has finished rendering and all HTML has been displayed, this event is raised. This is the time to manipulate DOM elements.
ShouldRender
- Called each time a component is rendered.