In this article we would like to deepen our focus on application development using blazor. We already covered Blazor in a previous article. This one continues our series on dotnet development with blazor.
Blazor is a powerful UI framework for building client-side applications using C#. With Blazor, you can create highly interactive web applications that leverage C# and .NET’s benefits, allowing developers to focus on productivity and maintainability. In this blog post, we’ll explore creating a simple airline booking application using Blazor in .NET 8 and provide insights into Blazor’s capabilities, advantages, and limitations.
Prerequisites
Before we dive into coding, make sure you have the following installed:
- .NET 8 SDK
- Visual Studio 2022 (or Visual Studio Code)
Setting Up the Project
Let’s start by creating a new Blazor WebAssembly application:
dotnet new blazorwasm -o AirlineBookingApp
cd AirlineBookingApp
Alternatively, in Visual Studio 2022:
- Go to File > New > Project.
- Choose Blazor WebAssembly App.
- Name it
AirlineBookingApp
and select .NET 8 as the framework.
Project Structure
Blazor projects are divided into three main parts:
- Pages: For routing and displaying different views.
- Components: For reusable UI pieces.
- Services: For handling data and business logic.
In our project, we will create the following components:
- Booking List: To view all available bookings.
- Booking Form: To create a new booking.
- Booking Details: To display details of a single booking.
Step 1: Creating Models
First, define a Booking
model to represent booking data. Create a new folder named Models
and add a file Booking.cs
:
// Models/Booking.cs
public class Booking
{
public int Id { get; set; }
public string PassengerName { get; set; }
public string FlightNumber { get; set; }
public DateTime DepartureDate { get; set; }
public string Destination { get; set; }
public string Origin { get; set; }
public bool IsConfirmed { get; set; }
}
This class represents our booking structure with essential properties.
Step 2: Creating a Service to Manage Bookings
In Blazor, services are used to manage data and handle business logic. Let’s create a BookingService
that manages our booking data.
- Create a
Services
folder. - Add a new file named
BookingService.cs
:
// Services/BookingService.cs
using System.Collections.Generic;
public class BookingService
{
private readonly List<Booking> bookings = new();
public IEnumerable<Booking> GetAllBookings() => bookings;
public Booking? GetBookingById(int id) => bookings.FirstOrDefault(b => b.Id == id);
public void AddBooking(Booking booking)
{
booking.Id = bookings.Count + 1;
bookings.Add(booking);
}
}
In Program.cs
, register the service:
// Program.cs
builder.Services.AddSingleton<BookingService>();
Step 3: Creating the UI
1. Booking List Component
Create a new component in the Pages
folder named BookingList.razor
:
@page "/bookings"
@inject BookingService BookingService
<h3>Available Bookings</h3>
@if (bookings is null || !bookings.Any())
{
<p>No bookings available.</p>
}
else
{
<ul>
@foreach (var booking in bookings)
{
<li>
<a href="/booking/@booking.Id">
@booking.PassengerName - @booking.FlightNumber
</a>
</li>
}
</ul>
}
@code {
private IEnumerable<Booking> bookings;
protected override void OnInitialized()
{
bookings = BookingService.GetAllBookings();
}
}
This component fetches all bookings from BookingService
and displays them in a list.
2. Booking Form Component
Create a new component named BookingForm.razor
in the Pages
folder:
@page "/new-booking"
@inject BookingService BookingService
@inject NavigationManager NavigationManager
<h3>Create a New Booking</h3>
<EditForm Model="newBooking" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<div>
<label>Passenger Name:</label>
<InputText @bind-Value="newBooking.PassengerName" />
</div>
<div>
<label>Flight Number:</label>
<InputText @bind-Value="newBooking.FlightNumber" />
</div>
<div>
<label>Departure Date:</label>
<InputDate @bind-Value="newBooking.DepartureDate" />
</div>
<div>
<label>Origin:</label>
<InputText @bind-Value="newBooking.Origin" />
</div>
<div>
<label>Destination:</label>
<InputText @bind-Value="newBooking.Destination" />
</div>
<button type="submit">Create Booking</button>
</EditForm>
@code {
private Booking newBooking = new();
private void HandleValidSubmit()
{
BookingService.AddBooking(newBooking);
NavigationManager.NavigateTo("/bookings");
}
}
This form binds to a Booking
instance, allowing users to fill in booking details and submit them. Upon submission, the form calls HandleValidSubmit
, adds the booking, and redirects to the booking list.
3. Booking Details Component
Add another component BookingDetails.razor
to show a single booking’s details:
@page "/booking/{Id:int}"
@inject BookingService BookingService
<h3>Booking Details</h3>
@if (booking is null)
{
<p>Booking not found.</p>
}
else
{
<div>
<strong>Passenger:</strong> @booking.PassengerName
</div>
<div>
<strong>Flight:</strong> @booking.FlightNumber
</div>
<div>
<strong>Departure:</strong> @booking.DepartureDate.ToShortDateString()
</div>
<div>
<strong>Origin:</strong> @booking.Origin
</div>
<div>
<strong>Destination:</strong> @booking.Destination
</div>
}
@code {
[Parameter]
public int Id { get; set; }
private Booking? booking;
protected override void OnParametersSet()
{
booking = BookingService.GetBookingById(Id);
}
}
This component fetches a booking by ID and displays its details. The @page
directive captures the Id
parameter from the URL.
Adding Navigation
Update the NavMenu.razor
component to include links to the new pages:
<NavLink href="/bookings" Match="NavLinkMatch.All">Bookings</NavLink><br><NavLink href="/new-booking">New Booking</NavLink>
Running the Application
Now, run the application by pressing F5 in Visual Studio or by running:
dotnet run
Navigate to /bookings
to view the booking list or to /new-booking
to create a new booking.
Pros and Cons of Blazor
Pros
- C# Everywhere: Unified language for both front-end and back-end, making code sharing and maintenance easier.
- Component-based Architecture: Allows for modular and reusable UI elements.
- Strong Typing: Leverages the type-safety and performance of C# and .NET.
- Integration with .NET Ecosystem: Easy to integrate with other .NET libraries and services.
Cons
- Large Initial Load Time: Blazor WebAssembly apps can have a larger initial load time, especially for first-time users.
- Browser Compatibility: While Blazor WebAssembly supports most modern browsers, performance may vary.
- Limited Support for Mobile: Blazor is optimized for web apps and currently lacks native mobile features.
Summary
In this post, we walked through creating an airline booking application using Blazor in .NET 8, covering service creation, component design, and data handling. Blazor’s approach to web development empowers .NET developers to create rich web applications using familiar languages and tools, though it still has room for improvement regarding performance and mobile support. Overall, Blazor in .NET 8 is a strong choice for building robust, component-driven web applications.