Introduction
Blazor is a revolutionary framework in the .NET ecosystem that allows developers to build interactive web applications without relying on JavaScript. Using C# and .NET, Blazor allows you to write client-side web applications that run in the browser via WebAssembly (WASM), or on the server while still maintaining a rich, dynamic user interface. We will explore how Blazor works, why it’s an exciting option for .NET developers, and provide a step-by-step guide to building a simple interactive web application using Blazor in .NET 9.
What is Blazor?
Blazor is a web framework developed by Microsoft as part of the .NET ecosystem. It enables developers to build interactive client-side web apps using C# and HTML, rather than JavaScript. Blazor works in two modes:
- Blazor WebAssembly: The application runs on the client-side within the browser. The Blazor WebAssembly application is compiled to WebAssembly, allowing .NET code to run directly in the browser.
- Blazor Server: The application runs on the server, with user interactions being sent to the server via SignalR, a real-time WebSockets communication protocol. Only the UI updates are sent to the client, ensuring a fast, scalable solution.
Why Use Blazor Instead of JavaScript?
Blazor presents several compelling reasons to consider it over JavaScript frameworks:
- Single Language Stack: With Blazor, you can use C# for both server-side logic and client-side interactivity, minimizing the need to learn and maintain multiple languages.
- Strong Type Checking: C# is a statically typed language, which means it can catch errors during compile time, reducing runtime issues that are common in JavaScript.
- Reusability: Blazor allows you to reuse .NET libraries, and you can even leverage existing .NET skills for building web apps.
- Integration with .NET Ecosystem: You can easily integrate with other .NET services, such as authentication, database access (via Entity Framework Core), and more.
- No JavaScript Runtime Dependency: Blazor WebAssembly runs directly in the browser, without the need for a JavaScript engine.
Prerequisites for Building Blazor Apps in .NET 9
Before we dive into coding, let’s ensure you have everything set up for Blazor development:
- Install .NET SDK 9.0: You need the latest .NET SDK (which includes .NET 9) to build Blazor apps. You can download it from the official .NET website.
- Visit https://dotnet.microsoft.com/download and choose .NET 9 SDK for your operating system.
- Visual Studio 2022 (or later) or Visual Studio Code: Visual Studio offers excellent tooling for Blazor development. However, you can also use Visual Studio Code if you prefer a lighter editor.
- Basic Knowledge of C# and HTML: Since Blazor apps use C# for logic and HTML for markup, you should be familiar with these technologies.
Step-by-Step Guide: Building a Blazor WebAssembly App
Let’s walk through the process of creating a simple interactive Blazor WebAssembly app.
Step 1: Create a New Blazor WebAssembly Project
- Open a terminal (Command Prompt or Visual Studio Code terminal).
- Run the following command to create a new Blazor WebAssembly app:
dotnet new blazorwasm -o BlazorApp
This command generates a new Blazor WebAssembly project in a folder called BlazorApp. You can also create a Blazor Server app by replacing blazorwasm with blazorserver.
Step 2: Open the Project in Visual Studio or Visual Studio Code
Open the newly created BlazorApp folder in Visual Studio or Visual Studio Code. If you are using Visual Studio Code, ensure you have the C# extension installed.
Understand the Project Structure
The generated project includes several important folders and files:
Pages: Contains Razor components, which are the building blocks of Blazor UI.wwwroot: Static files like images, CSS, JavaScript, etc.Program.cs: The entry point for the app.App.razor: The root component that configures routing and layout._Imports.razor: Shared Razor imports (e.g., namespaces) for the entire app.
Step 3: Building the UI
Let’s modify the default template to create a simple interactive counter app that increments a counter value without using JavaScript.
- Open
Pages/Counter.razor. - Replace the existing code with the following:
@page "/Counter"
@using System
<h3>Counter</h3>
<p>Current count: @count</p>
<button class="btn btn-primary" @onclick="IncrementCount">Increment</button>
@code {
private int count = 0;
private void IncrementCount()
{
count++;
}
}
@page "/": Specifies that this component is the default route of the app.@count: This binds the value of thecountvariable to the UI.@onclick="IncrementCount": This binds theIncrementCountmethod to the button click event. It increments the counter when clicked.
Step 4: Running the Application
In the terminal, navigate to the BlazorApp folder (if not already there). And Run the following command to start the application:
dotnet run
This will start a local development server, and you can open your browser to https://localhost:5001 to see the app in action.
You will see a simple webpage with a button that, when clicked, increments the counter.
Step 5: Add Styling (Optional)
To make the app look better, you can add some styling to the page. Open the wwwroot/css/app.css file and add the following styles:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 20px;
}
h3 {
color: #333;
}
.btn {
margin-top: 10px;
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
}
.btn:hover {
background-color: #0056b3;
}
.form-control {
margin-top: 10px;
}
Now, when you reload the page, you will see the button with better styling.
Step 6: Enhancing the App with More Interactivity
Let’s add a simple form to input a name and greet the user. Modify Counter.razor again as follows:
@page "/Counter"
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<hr/>
<h4>Enter your name:</h4>
<input type="text" @bind="userName" class="form-control" />
<p>Hello, @userName!</p>
@code {
private int currentCount = 0;
private string userName = "";
private void IncrementCount()
{
currentCount++;
}
}
@bind="userName": This binds theinputfield to theuserNamevariable, so as the user types, the variable automatically updates.- The greeting message
Hello, @userName!updates in real time as the user enters their name.
Output:
Step 7: Debugging and Testing
- Hot Reload: With Blazor, you can use hot reload to instantly see changes made to your app without restarting it. This is extremely helpful during development.
- Browser Developer Tools: Blazor WebAssembly runs in the browser, so you can use browser developer tools (F12) to inspect elements, debug JavaScript (if any), and see network activity.
Conclusion
Blazor offers a fresh way to build interactive, modern web applications without writing JavaScript. By using .NET 9 and C#, you can share code between client and server, and utilize the full power of the .NET ecosystem in the browser. In this tutorial, you’ve learned how to create a Blazor WebAssembly app, implement basic interactivity, and use C# for both the frontend and backend of your application. Whether you are new to Blazor or an experienced .NET developer, this framework opens up exciting possibilities for building high-performance web apps with a unified development experience
