Blazor is a Microsoft framework that allows building interactive web applications using C# instead of JavaScript, leveraging .NET and WebAssembly for modern applications.
Types of Blazor
Blazor WebAssembly (WASM)
Runs C# directly in the browser using WebAssembly.
Blazor Server
Runs the code on the server and sends updates to the browser in real-time via SignalR.
Create project
Create a Blazor WebAssembly project
To create a basic Blazor WebAssembly project.
dotnet new blazorwasm -o MyBlazorProject
Create a Blazor Server project
To create a Blazor Server project.
dotnet new blazorserver -o MyBlazorServerProject
Components in Blazor
Components in Blazor
Components are the fundamental unit of Blazor. They are written in .razor
files and can include C#, HTML, and Razor.
<h3>Hello, Blazor</h3>
@code {
string message = "Welcome to Blazor";
}
Communicating between components
Properties and parameters can be used to communicate data between components.
<h3>@Title</h3>
@code {
[Parameter]
public string Title { get; set; }
}
To pass parameters to a component:
<CustomComponent Title="Hello Blazor" />
Lifecycle of components
Lifecycle methods
Blazor provides several lifecycle methods to control component logic:
OnInitialized() Runs once when the component is initialized.
OnParametersSet() Runs every time parameters change.
OnAfterRender() Runs after the component has been rendered.
@code {
protected override void OnInitialized() {
Console.WriteLine("Component initialized");
}
}
Data Binding
One-way binding
One-way data binding is used to display data in the UI.
<p>@message</p>
@code {
string message = "Hello from Blazor";
}
Two-way binding
Two-way data binding allows changes in the UI to be reflected in the code and vice versa. It uses the @bind
attribute.
<input @bind="message" />
<p>@message</p>
@code {
string message = "Hello Blazor";
}
Event Handling
Common events
Blazor uses the @
prefix to handle browser events, such as button clicks and text changes.
<button @onclick="HandleClick">Click me</button>
@code {
void HandleClick() {
Console.WriteLine("Button clicked!");
}
}
EventCallback
Blazor allows event communication between parent and child components with EventCallback
.
Child component:
<button @onclick="OnClick">Click me</button>
@code {
[Parameter]
public EventCallback OnClick { get; set; }
}
Parent component:
<ChildComponent OnClick="HandleChildClick" />
@code {
void HandleChildClick() {
Console.WriteLine("The child component's button was clicked");
}
}
Conditional rendering and loops
Conditional rendering
Blazor allows showing or hiding elements based on logical conditions.
@if (show) {
<p>This is a conditional paragraph</p>
}
Rendering with loops
Use @foreach
to iterate over collections and render multiple elements.
@foreach (var item in list) {
<p>@item</p>
}
@code {
List<string> list = new List<string> { "Item 1", "Item 2", "Item 3" };
}
Common directives in Blazor
@page
Defines a route in a Razor component, making it a page.
@page "/home"
<h3>Home Page</h3>
@code
Allows writing C# blocks within a .razor
component.
@code {
string message = "Hello Blazor";
}
@inject
Injects services into components for dependency access.
@inject TimeService Time
<p>Current time: @Time.GetCurrentTime()</p>
Routing in Blazor
Route configuration
In a .razor
component, you can define routes with @page
.
@page "/about"
<h3>About Page</h3>
Programmatic navigation
You can redirect programmatically using NavigationManager
.
@inject NavigationManager navManager
<button @onclick="NavigateToHome">Go to Home</button>
@code {
void NavigateToHome() {
navManager.NavigateTo("/home");
}
}
Dependency Injection
Configuring services
Blazor supports dependency injection through the service container in Program.cs
.
builder.Services.AddSingleton<TimeService>();
Injecting services in a component
To use a service within a component, @inject
is used.
@inject TimeService Time
<p>The time is: @Time.GetCurrentTime()</p>
@code {
// additional logic
}
Forms and Validation
Creating a simple form
Blazor makes it easy to create forms with two-way binding and submit events.
<EditForm Model="@user" OnValidSubmit="HandleSubmit">
<InputText id="name" @bind-Value="user.Name" />
<button type="submit">Submit</button>
</EditForm>
@code {
User user = new User();
void HandleSubmit() {
Console.WriteLine("Form submitted");
}
}
Form validation
Blazor includes support for validation using data annotation attributes (DataAnnotations
).
public class User {
[Required]
public string Name { get; set; }
}
Reusable components
Parameterized components
You can create reusable components by passing parameters.
<h3>@Title</h3>
@code {
[Parameter]
public string Title { get; set; }
}
Nested components
You can use components within other components:
<ChildComponent Title="My Component" />
Blazor and JavaScript
Invoking JavaScript from Blazor
Blazor allows interoperability with JavaScript through IJSRuntime
.
@inject IJSRuntime js
<button @onclick="ShowAlert">Show Alert</button>
@code {
async Task ShowAlert() {
await js.InvokeVoidAsync("alert", "Hello from Blazor!");
}
}
Invoking Blazor from JavaScript
You can call C# methods from JavaScript using DotNet.invokeMethodAsync
.
DotNet.invokeMethodAsync('AssemblyName', 'MethodInCSharp');
Deploying Blazor applications
Blazor WebAssembly
To publish a WebAssembly application, use the following command:
dotnet publish --configuration Release
Blazor Server
To publish a Blazor Server application:
dotnet publish --configuration Release --output ./public
Debugging and Optimization
Debugging in Blazor WebAssembly
You can debug Blazor WASM applications using browser developer tools and Visual Studio.
Load optimization
Use release mode publishing to optimize application loading.
dotnet publish -c Release