Blazor is a framework to build interactive web apps using C# (instead of JavaScript).
Runs in the browser via WebAssembly (client-side) or on the server (server-side).
Uses Razor syntax (HTML + C#) to create components.
Hosting Models
| Blazor WebAssembly | Blazor Server | | --- | --- | | Runs C# code directly in the browser | Runs C# code on the server | | Needs WebAssembly support | Uses SignalR for real-time updates | | Good for static sites | Good for dynamic apps |
Create Your First Blazor App
Step 1: Create a New Project
Open a terminal and run:
dotnet new blazorwasm -o HelloBlazor
cd HelloBlazor
Step 2: Run the App
dotnet run
Understand the Project Structure
Here’s what the HelloBlazor
folder contains:
HelloBlazor/
├── Pages/ # Contains Razor components (e.g., Index.razor)
├── Shared/ # Reusable components (e.g., MainLayout.razor)
├── wwwroot/ # Static files (CSS, images)
├── Program.cs # App startup logic
├── App.razor # Root component for routing
Modify the Home Page (Hello World)
Let’s edit the default home page.
Step 1: Open Pages/Index.razor
Replace its content with:
@page "/"
Hello, Blazor!
Today is @DateTime.Now.ToShortDateString()
<button @onclick="ShowAlert">Click Me
@code { private void ShowAlert() { Console.WriteLine("Button clicked!"); // Log to browser console } }
Step 2: Run Again
dotnet run
Key Takeaways
Components: Blazor apps are built using
.razor
files (e.g.,Index.razor
).Razor Syntax: Mix HTML with C# using
@
(e.g.,@
DateTime.Now
).Event Handling: Use
@onclick
,@oninput
to handle user actions.
Practice Task
Modify the Counter Component:
Open
Pages/Counter.razor
.Change the button text to "Increment by 1".
Make the counter start at 10 instead of 0.
Solution
@page "/counter"
Counter
Current count: @currentCount
Increment by 1
@code { private int currentCount = 10; // Start at 10 private void IncrementCount() => currentCount++; }
Common Issues (For Beginners)
Port Conflicts: If
dotnet run
fails, usedotnet run --urls=
http://localhost:5000
to change the port.Browser Caching: Force-refresh the page (Ctrl + F5) if changes don’t appear.
Missing Dependencies: Ensure the .NET SDK is installed correctly (
dotnet --version
should work).