Building Your First Blazor WebAssembly Application: A Step-by-Step Guide

Blazor is a powerful framework that allows you to write interactive full-stack web applications using C# and HTML, without needing to write a single line of JavaScript. Blazor WebAssembly is one of two Blazor hosting architectures, WebAssembly and Server. This tutorial will teach you how to write your first Blazor WebAssembly application.
Prerequisites
Before starting, make sure you have the following software installed:
- .NET SDK 6.0 or later
Download .NET - Visual Studio Code with the C# extension (alternatively you can use Visual Studio)
Download Visual Studio Code
Create a new Blazor WebAssembly project
dotnet new blazorwasm -o MyFirstBlazorApp
This command creates a new Blazor WebAssembly project named "MyFirstBlazorApp" in a new folder with the same name.

Change to the newly created project directory:
cd MyFirstBlazorApp
Explore the project structure
The Blazor WebAssembly project has a predefined structure with various files and folders. The most important ones to note are:
wwwroot
: Contains static files such as HTML, CSS, and JavaScript.

Pages
: Contains the Razor components that represent pages in your application.

Shared
: Contains shared Razor components, such as the layout and navigation components.

Program.cs
: The entry point for your application.
Run the application
In Visual Studio Code, navigate to Terminal -> New Terminal, then run the following command:
dotnet watch run

This command will build and launch your Blazor application in your default web browser at the address https://localhost:5001/
. You should see the default Blazor template with a counter and fetch data examples.

Customize the application
Now, let's customize our application by adding a new page that displays a personalized welcome message.
- In the
Pages
folder, create a new Razor component namedWelcome.razor
. - Add the following code to
Welcome.razor
:
@page "/welcome"
<h3>Welcome, @Name!</h3>
<div>
<label for="nameInput">Enter your name: </label>
<input id="nameInput" @bind="@Name" @bind:event="oninput" placeholder="Type your name..." />
</div>
@code {
private string Name { get; set; } = "Guest";
}
This code defines a simple welcome message that updates when the user types a value in the input element. The @bind
directive enables two-way data binding between the input element and the Name
property in the C# code block.
3. Update the navigation menu to include the new Welcome page. Open Shared/NavMenu.razor
and add a new list item with a link to the welcome page:
<li class="nav-item px-3">
<NavLink class="nav-link" href="welcome">
<span class="oi oi-person" aria-hidden="true"></span> Welcome
</NavLink>
</li>

Congratulations! You've created your first Blazor WebAssembly application!