Introduction to Blazor
Blazor is a web framework for building interactive client-side web UIs with .NET and C#. Blazor allows developers to create rich, interactive web applications without needing to write JavaScript. You can run Blazor apps in two main ways:
- Blazor Server: The application runs on the server, and UI updates are sent to the client over a real-time connection (SignalR).
- Blazor WebAssembly (WASM): The application runs directly in the browser using WebAssembly.
This documentation provides a comprehensive guide to developing applications with Blazor, covering its core concepts, features, and best practices.
Getting Started
To begin with Blazor, you'll need the .NET SDK installed. You can create a new Blazor project using the .NET CLI:
dotnet new blazorwasm -o MyBlazorApp
This command creates a new Blazor WebAssembly project named `MyBlazorApp`. You can then navigate into the project directory and run it:
cd MyBlazorApp
dotnet run
For Blazor Server projects, use:
dotnet new blazorserver -o MyBlazorServerApp
Components
Blazor applications are built using reusable UI components. These components are typically defined in `.razor` files, which combine HTML markup, C# code, and CSS.
Here's a simple example of a Blazor component:
@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
The `@page` directive enables routing for the component. The `@onclick` directive binds a C# method to the button's click event.
Routing
Blazor uses a component-based routing system. You can make components available at specific URLs using the @page
directive.
To navigate between components, you can use the NavLink
component, which renders an <a>
tag and automatically adds an "active" CSS class when its href
matches the current URL.
<NavLink href="/" Match="NavLinkMatch.All">
<span class="oi oi-home" aria-hidden="true"></span> Home
</NavLink>
Data Binding
Blazor supports one-way and two-way data binding.
- One-way binding (
@someVariable
) renders data. - Two-way binding (
@bind-Value
) synchronizes a component's property with an input element's value.
<input @bind="Name" />
<p>Hello, @Name!</p>
@code {
public string Name { get; set; }
}
Event Handling
You can handle browser events like clicks, key presses, and form submissions directly in C# using Blazor's event binding syntax (e.g., @onclick
, @onchange
, @oninput
).
Component Lifecycle
Blazor components have a well-defined lifecycle. Key methods include:
SetParametersAsync
: Called when parameters are set on a component.OnInitialized
: Called after parameters are initialized and before the component is rendered for the first time.OnInitializedAsync
: Asynchronous version ofOnInitialized
.OnParametersSet
: Called after parameters are set and when they change.OnParametersSetAsync
: Asynchronous version ofOnParametersSet
.ShouldRender
: Allows you to control whether the component should re-render.OnAfterRender
: Called after the component has rendered.OnAfterRenderAsync
: Asynchronous version ofOnAfterRender
.
Forms and Validation
Blazor provides components and mechanisms for building forms and handling validation. The EditForm
component is central to form handling, and you can use data annotations for validation rules.
JavaScript Interop
If you need to call JavaScript functions from your Blazor code or vice-versa, Blazor provides a robust JavaScript interop API. You can inject IJSRuntime
to execute JavaScript.
@inject IJSRuntime JSRuntime
<button @onclick="ShowAlert">Show Alert</button>
@code {
private async Task ShowAlert()
{
await JSRuntime.InvokeVoidAsync("alert", "Hello from Blazor!");
}
}
State Management
For managing application state that needs to be shared across multiple components, consider using services, scoped services, or dedicated state management libraries.
Deployment
Blazor apps can be deployed to various hosting environments, including Azure App Service, Docker containers, and static web hosting. The deployment process depends on whether you are using Blazor Server or Blazor WebAssembly.