Blazor is a framework for building interactive web applications using C# and .NET. It allows developers to create rich web UIs using C# instead of JavaScript. Blazor can run client-side in the browser using WebAssembly or server-side in ASP.NET Core.

Key Concepts

  1. What is Blazor?

  • Blazor WebAssembly (WASM): Runs client-side in the browser on WebAssembly. This allows for a rich, interactive experience without the need for a server round trip.
  • Blazor Server: Runs server-side and handles UI interactions over a SignalR connection. This allows for a thin client with the logic running on the server.

  1. Setting Up a Blazor Project

  • Prerequisites: Ensure you have .NET SDK installed.
  • Creating a Blazor Project: Use Visual Studio or the .NET CLI to create a new Blazor project.

  1. Blazor Components

  • Component Structure: Blazor applications are built using components. Each component is a self-contained chunk of UI.
  • Razor Syntax: Blazor uses Razor syntax to define components, which combines HTML and C#.

  1. Data Binding

  • One-way Binding: Data flows from the component to the UI.
  • Two-way Binding: Data flows both ways, allowing the UI to update the component and vice versa.

  1. Event Handling

  • Event Callbacks: Handle user interactions such as button clicks.
  • Event Parameters: Pass parameters to event handlers.

  1. Dependency Injection

  • Service Registration: Register services in the Startup class.
  • Service Injection: Inject services into components.

  1. Routing

  • Route Templates: Define routes using the @page directive.
  • Navigation: Use the NavigationManager to navigate between components.

  1. Forms and Validation

  • Form Components: Use built-in form components like EditForm, InputText, etc.
  • Validation: Implement validation using data annotations.

Practical Example

Creating a Blazor WebAssembly Project

  1. Using Visual Studio:

    • Open Visual Studio and select "Create a new project".
    • Choose "Blazor WebAssembly App" and click "Next".
    • Configure the project name and location, then click "Create".
  2. Using .NET CLI:

    dotnet new blazorwasm -o BlazorApp
    cd BlazorApp
    dotnet run
    

Basic Blazor Component

Create a new component named Counter.razor:

@page "/counter"

<h3>Counter</h3>

<p>Current count: @currentCount</p>

<button @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

Explanation:

  • @page "/counter": Defines the route for the component.
  • @currentCount: Displays the current count.
  • @onclick="IncrementCount": Binds the button click event to the IncrementCount method.
  • @code { ... }: Contains the C# code for the component.

Data Binding Example

Create a new component named DataBinding.razor:

@page "/databinding"

<h3>Data Binding</h3>

<p>Enter your name: <input @bind="name" /></p>
<p>Hello, @name!</p>

@code {
    private string name = string.Empty;
}

Explanation:

  • @bind="name": Two-way binds the input value to the name field.
  • @name: Displays the value of the name field.

Practical Exercises

Exercise 1: Create a To-Do List Component

Task: Create a component that allows users to add items to a to-do list and display the list.

Solution:

  1. Create a new component named Todo.razor:
@page "/todo"

<h3>To-Do List</h3>

<input @bind="newItem" placeholder="Enter a new item" />
<button @onclick="AddItem">Add</button>

<ul>
    @foreach (var item in items)
    {
        <li>@item</li>
    }
</ul>

@code {
    private string newItem = string.Empty;
    private List<string> items = new List<string>();

    private void AddItem()
    {
        if (!string.IsNullOrWhiteSpace(newItem))
        {
            items.Add(newItem);
            newItem = string.Empty;
        }
    }
}

Explanation:

  • @bind="newItem": Binds the input value to the newItem field.
  • @onclick="AddItem": Binds the button click event to the AddItem method.
  • @foreach (var item in items) { ... }: Iterates over the items list and displays each item.

Exercise 2: Implement Form Validation

Task: Create a form with validation for a user registration component.

Solution:

  1. Create a new component named Register.razor:
@page "/register"

<h3>Register</h3>

<EditForm Model="@user" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div>
        <label>Username:</label>
        <InputText id="username" @bind-Value="user.Username" />
        <ValidationMessage For="@(() => user.Username)" />
    </div>

    <div>
        <label>Password:</label>
        <InputText id="password" @bind-Value="user.Password" type="password" />
        <ValidationMessage For="@(() => user.Password)" />
    </div>

    <button type="submit">Register</button>
</EditForm>

@code {
    private User user = new User();

    private void HandleValidSubmit()
    {
        // Handle valid form submission
    }

    public class User
    {
        [Required]
        [StringLength(100, MinimumLength = 3)]
        public string Username { get; set; }

        [Required]
        [StringLength(100, MinimumLength = 6)]
        public string Password { get; set; }
    }
}

Explanation:

  • EditForm: Wraps the form and binds it to the user model.
  • DataAnnotationsValidator: Enables validation using data annotations.
  • ValidationSummary: Displays a summary of validation errors.
  • InputText: Binds input fields to the user model properties.
  • ValidationMessage: Displays validation messages for specific fields.

Conclusion

In this section, we covered the basics of Blazor, including setting up a project, creating components, data binding, event handling, dependency injection, routing, and form validation. Blazor provides a powerful framework for building interactive web applications using C# and .NET, allowing developers to leverage their existing skills and knowledge.

Next, we will explore more advanced topics in Blazor, such as state management, component lifecycle, and performance optimization.

© Copyright 2024. All rights reserved