Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Web Development with Blazor, 2e - Second Edition
Web Development with Blazor, 2e - Second Edition

Web Development with Blazor, 2e: A practical guide to start building interactive UIs with C# 11 and .NET 7, Second Edition

By Jimmy Engström
€25.99 €17.99
Book Mar 2023 360 pages 2nd Edition
eBook
€25.99 €17.99
Print
€31.99
Subscription
€14.99 Monthly
eBook
€25.99 €17.99
Print
€31.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Mar 16, 2023
Length 360 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781803241494
Vendor :
Microsoft
Category :
Table of content icon View table of contents Preview book icon Preview Book

Web Development with Blazor, 2e - Second Edition

Creating Your First Blazor App

In this chapter, we will set up our development environment so that we can start developing Blazor apps. We will create our first Blazor app and go through the project structure, highlighting the differences between Blazor Server and Blazor WebAssembly projects.

By the end of this chapter, you will have a working development environment and have created both a Blazor Server app and a Blazor WebAssembly app.

In this chapter, we will cover the following:

  • Setting up your development environment
  • Creating our first Blazor application
  • Using the command line
  • Figuring out the project structure

Technical requirements

We will create a new project (a blog engine) and will continue working on that project throughout the book.

You can find the source code for this chapter’s result at https://github.com/PacktPublishing/Web-Development-with-Blazor-Second-Edition/tree/main/Chapter02.

Setting up your development environment

In this book, the focus will be on Windows development, and any screenshots are going to be from Visual Studio (unless stated otherwise). But since .NET 7 is cross-platform, we will go through how to set up your development environment on Windows, macOS, and Linux.

The go-to link for all the platforms can be found at https://visualstudio.microsoft.com/.

We can download Visual Studio, Visual Studio Code, or Visual Studio for Mac from the web page.

Windows

On Windows, we have many different options for developing Blazor applications. Visual Studio 2022 is the most powerful tool we can use.

There are three different editions, which are as follows:

  • Community 2022
  • Professional 2022
  • Enterprise 2022

In short, the Community Edition is free, while the others cost money. The Community Edition does have some limitations, and we can compare the different editions here: https://visualstudio.microsoft.com/vs/compare/.

For this book, we can use any of these versions. Take the following steps:

  1. Download Visual Studio 2022 from https://visualstudio.microsoft.com/vs/. Choose the version that is right for you.
  2. Install Visual Studio and during the installation, make sure to select ASP.NET and web development, as shown in Figure 2.1:

Figure 2.1: Visual Studio 2022 installation on Windows

  1. To the right is a list of all the components that will be installed. Check .NET WebAssembly Build Tools.

We can also use Visual Studio Code to develop Blazor on Windows, but we won’t discuss the installation process for Windows.

macOS

On macOS, we also have some options. Visual Studio for Mac is the most powerful IDE we can use.

Download Visual Studio for Mac from https://visualstudio.microsoft.com/vs/mac/ as follows:

  1. Click on the Download Visual Studio for Mac button.
  2. Open the file that we downloaded.

Make sure to select .NET, as shown in Figure 2.2:

No description available.

Figure 2.2: Visual Studio for Mac installation screen

Since Visual Studio Code is a cross-platform software, we can use it here as well.

Linux (or macOS or Windows)

Visual Studio Code is cross-platform, which means we can use it on Linux, macOS, or Windows.

The different versions are available at https://code.visualstudio.com/Download.

Once installed, we also need to add two extensions:

  1. Open Visual Studio Code and press Ctrl + Shift + X.
  2. Search for C# for Visual Studio Code (powered by OmniSharp) and click Install.
  3. Search for JavaScript Debugger (Nightly) and click Install.

To create a project, we can use the .NET CLI, which we will return to throughout this book, but we won’t do a deep dive into the .NET CLI.

Now that everything is set up, let’s create our first app.

Creating our first Blazor application

Throughout the book, we will create a blog engine. There won’t be a lot of business logic that you’ll have to learn; the app is simple to understand but will touch base on many of the technologies and areas you will be faced with when building a Blazor app.

The project will allow visitors to read blog posts and search for them. It will also have an admin site where you can write a blog post, which will be password-protected.

We will make the same app for both Blazor Server and Blazor WebAssembly, and I will show you the steps you need to do differently for each platform.

IMPORTANT NOTE

This guide will use Visual Studio 2022 from now on, but other platforms have similar ways of creating projects.

Exploring the templates

In .NET 7, we got more templates. We will explore them further in Chapter 4, Understanding Basic Blazor Components. This chapter will give you a quick overview. In .NET 7 we have 4 Blazor templates, two Blazor Server, and two Blazor WebAssembly. We also have one Blazor Hybrid (.NET MAUI), but we will get back to it in Chapter 18, Visiting .NET MAUI.

Blazor Server App

The Blazor Server App template gives us (as the name implies) a Blazor Server app. It contains a couple of components to see what a Blazor app looks like and some basic setup and menu structure. It also contains code for adding Bootstrap, Isolated CSS, and things like that (See Chapter 9, Sharing Code and Resources).

This is the template we will use in the book to understand better how things go together.

Blazor WebAssembly App

The Blazor WebAssembly App template gives us (as the name implies) a Blazor WebAssembly app. Just like the Blazor Server App template, it contains a couple of components to see what a Blazor app looks like and some basic setup and menu structure. It also contains code for adding Bootstrap, Isolated CSS, and things like that (See Chapter 9, Sharing Code and Resources).

This is the template we will use in the book to understand better how things go together.

Blazor Server App Empty

The Blazor Server App Empty template is a basic template that contains what is essential to run a Blazor Server App.

It doesn’t contain Isolated CSS and things like that. When starting an actual project, this is probably the template to use. But it does require us to implement things we might need that the non-empty templates will give us.

Blazor WebAssembly App Empty

The Blazor WebAssembly App Empty template is a basic template that contains what is essential to run a Blazor WebAssembly App.

It doesn’t contain Isolated CSS and things like that. When starting an actual project, this is probably the template to use. But it does require us to implement things we might need that the non-empty templates will give us.

Creating a Blazor Server application

To start, we will create a Blazor Server application and play around with it:

  1. Start Visual Studio 2022, and you will see the following screen:

Figure 2.3: Visual Studio startup screen

  1. Press Create a new project, and in the search bar, type blazor.
  2. Select Blazor Server App from the search results and press Next:

Figure 2.4: The Visual Studio Create a new project screen

  1. Now name the project (this is the hardest part of any project, but fear not, I have done that already!). Name the application BlazorServer, change the solution name to MyBlog, and press Next:

Figure 2.5: The Visual Studio Configure your new project screen

  1. Next, choose what kind of Blazor app we should create. Select .NET 7.0 (Standard Term Support) from the dropdown menu and press Create:

Figure 2.6: Visual Studio screen for creating a new Blazor app

  1. Now run the app by pressing Ctrl + F5 (we can also find it under Debug | Start without debugging).

Congratulations! You have just created your first Blazor Server application. The site should look something like in Figure 2.7:

Figure 2.7: A new Blazor Server server-side application

Explore the site a bit, navigate to Counter and Fetch data to get a feeling for the load times, and see what the sample application does.

The sample application has some sample data ready for us to test.

This is a Blazor Server project, which means that for every trigger (for example, a button press), a command will be sent via SignalR over to the server. The server will rerender the component, send the changes back to the client, and update the UI.

Press F12 in your browser (to access the developer tools), switch to the Network tab and then reload the page (F5). You’ll see all the files that get downloaded to the browser.

In Figure 2.8, you can see some of the files that get downloaded:

Figure 2.8: The Network tab in Microsoft Edge

The browser downloads the page, some CSS, and then blazor.server.js, which is responsible for setting up the SignalR connection back to the server. It then calls the negotiate endpoint (to set up the connections).

The call to _blazor?id= (followed by a bunch of letters) is a WebSocket call, which is the open connection that the client and the server communicate through.

If you navigate to the Counter page and press the Click me button, you will notice that the page won’t be reloaded. The trigger (click event) is sent over SignalR to the server, and the page is rerendered on the server and gets compared to the render tree, and only the actual change is pushed back over the WebSocket.

For a button click, three calls are being made:

  • The page triggers the event (for example, a button click).
  • The server responds with the changes.
  • The page then acknowledges that the Document Object Model (DOM) has been updated.

In total, 600 bytes (this example is from the Counter page) are sent back and forth for a button click.

We have created a solution and a Blazor Server project and tried them out. Next up, we will add a Blazor WebAssembly app to that solution.

Creating a WebAssembly application

Now it is time to take a look at a WebAssembly app. We will create a new Blazor WebAssembly app and add it to the same solution as the Blazor Server app we just created:

  1. Right-click on the MyBlog solution and select Add | New Project.
  2. Search for blazor, select Blazor WebAssembly App in the search results, and press Next:

Figure 2.9: The Visual Studio Add a new project screen

  1. Name the app BlazorWebAssembly. Leave the location as is (Visual Studio will put it in the correct folder by default) and press Create:

Figure 2.10: The Visual Studio Configure your new project screen

  1. On the next screen, select .NET 7.0 (Standard Term Support) from the dropdown.
  2. In this dialog box, two new choices that were not available in the Blazor Server template appear. The first option is ASP.NET Core hosted, which will create an ASP.NET backend project and will host the WebAssembly app, which is good if you want to host web APIs for your app to access; you should check this box.
  3. The second option is Progressive Web Application, which will create a manifest.json file and a service-worker.js file that will make your app available as a Progressive Web Application (PWA). Make sure the Progressive Web Application option is checked as well, and then press Create:

Figure 2.11: Visual Studio screen for creating a new Blazor app

  1. Right-click on the WebAssembly.Server project and select Set as Startup Project.

    NOTE:

    It can be confusing that this project also has Server in the name.

    Since we chose ASP.NET Core hosted when we created the project, we are hosting the backend for our client-side (WebAssembly) in WebAssembly.Server, and it is not related to Blazor Server.

    Remember that if you want to run the WebAssembly app, you should run the WebAssembly.Server project; that way, we know the backend ASP.NET Core project will also run.

  1. Run the app by pressing Ctrl + F5 (start without debugging).

Congratulations! You have just created your first Blazor WebAssembly application, as shown in Figure 2.12:

Figure 2.12: A new Blazor WebAssembly app

Explore the site by clicking the Counter and Fetch data links. The app should behave in the same way as the Blazor Server version.

Press F12 in your browser (to access the developer tools), switch to the Network tab, and reload the page (F5); you’ll see all the files downloaded to the browser.

In Figure 2.13, you can see some of the files that got downloaded:

Figure 2.13: The Network tab in Microsoft Edge

In this case, when the page gets downloaded, it will trigger a download of the blazor.webassembly.js file. Then, blazor.boot.json gets downloaded. Figure 2.14 shows an example of part of blazor.boot.json:

Figure 2.14: Part of the blazor.boot.json file

The most important thing blazor.boot.json contains is the entry assembly, which is the name of the DLL the browser should start executing. It also includes all the framework DLLs the app needs to run. Now our app knows what it needs to start up.

The JavaScript will then download dotnet.7.0.*.js, which will download all the resources mentioned in blazor.boot.json: this is a mix of your code compiled to a .NET Standard DLL, Microsoft .NET Framework code, and any community or third-party DLLs you might use. The JavaScript then downloads dotnet.wasm, the Mono runtime compiled to WebAssembly, which will start booting up your app.

If you watch closely, you might see some text when you reload your page saying Loading. Between Loading showing up and the page finishing loading, JSON files, JavaScript, WebAssembly, and DLLs are downloaded, and everything boots up. According to Microsoft Edge, it takes 1.8 seconds to run in debug mode and with unoptimized code.

Now we have the base for our project, including a Blazor WebAssembly version and a Blazor Server version. Throughout this book, we will use Visual Studio, but there are other ways to run your Blazor site, such as using the command line. The command line is a super powerful tool, and in the next section, we will take a look at how to set up a project using the command line.

Using the command line

With .NET 5, we got a super powerful tool called dotnet.exe. Developers that have used .NET Core before will already be familiar with the tool, but with .NET 5, it is no longer exclusively for .NET Core developers.

It can do many things Visual Studio can do, for example, creating projects, adding and creating NuGet packages, and much more. In the following example, we will create a Blazor Server and a Blazor WebAssembly project.

Creating projects using the command line

The following steps are to demonstrate the power of using the command line. We will not use this project later in the book, so if you don’t want to try it, go ahead and skip this section. To create a solution with Blazor server and Blazor WebAssembly projects like the one we just did, we can run this command:

dotnet new blazorserver -o BlazorServer
dotnet new blazorwasm -o BlazorWebAssembly --pwa –hosted

Here, dotnet is the command. To create a new project, we use the new parameter.

blazorserver is the template’s name, and -o is the output folder (in this case, the project will be created in a subfolder called BlazorServer).

The second line uses the template blazorwasm that created a Blazor WebAssembly project, and it uses the pwa flag to make it a Progressive web app and the hosted flag to get an ASP.NET hosted backend.

We also need to create a solution for our projects, and we can do that from the command line by using the template sln.

dotnet new sln --name MyBlog

We also need to add the projects we created, which are one Blazor Server project and 3 Blazor WebAssembly projects.

dotnet sln MyBlog.sln add ./BlazorWebAssembly\Server\BlazorWebAssembly.Server.csproj
dotnet sln MyBlog.sln add ./BlazorWebAssembly\Client\BlazorWebAssembly.Client.csproj
dotnet sln MyBlog.sln add .\BlazorWebAssembly\Shared\BlazorWebAssembly.Shared.csproj
dotnet sln MyBlog.sln add .\BlazorServer\BlazorServer.csproj

The dotnet command is super powerful; for some scenarios, it makes sense to use it. I mostly use the UI in Visual Studio, but it’s important to know we have the dotnet tool we can use.

NOTE: THE .NET CLI

The idea is that you should be able to do everything from the command line. If you prefer working with the command line, you should check out the .NET CLI; you can read more about the .NET CLI here: https://docs.microsoft.com/en-us/dotnet/core/tools/.

Let’s go back to the Blazor template, which has added a lot of files for us. In the next section, we will look at what Visual Studio has generated for us.

Figuring out the project structure

Now it’s time to look at the different files and how they may differ in different projects. Take a look at the code in the two projects we just created (in the Creating our first Blazor app section) while we go through them.

Program.cs

Program.cs is the first class that gets called. It also differs between Blazor Server and Blazor WebAssembly.

WebAssembly Program.cs

In the WebAssembly.Client project, there is a file called Program.cs, and it looks like this:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();

Program.cs uses top-level statements without any classes or methods. By using top-level statements, C# understands that this is the application’s entry point. It will look for a div with the ID “app” and add (render) the App component inside the div, and the whole single-page application site will be rendered inside of the App component (we will get back to that component later in the chapter).

It adds a component called HeadOutlet and this component is for handling changing the head tag. Things that are located in the head tag are Title and head tags (to name a few). The Headoutlet gives us the ability to change the title of our page as well as meta tags.

It adds HttpClient as a scoped dependency. In Chapter 3, Managing State – Part 1, we will dig deeper into dependency injection, but for now, it is a way to abstract the creation of objects and types by injecting objects (dependencies), so we don’t create objects inside a page. The objects get passed into the page/classes instead, making testing easier, and the classes don’t have any dependencies we don’t know about.

The WebAssembly version is running in the browser, so it can only get data by making external calls (to a server, for example); therefore, we need to be able to access HttpClient. WebAssembly is not allowed to make direct calls to download data. Therefore, HttpClient is a special implementation for WebAssembly that will make JavaScript interop calls to download data.

As I mentioned before, WebAssembly is running in a sandbox, and to be able to communicate outside of this sandbox, it needs to go through appropriate JavaScript/browser APIs.

Blazor Server Program.cs

Blazor Server projects look a bit different (but do pretty much the same thing). In the BlazorServer project, the Program.cs file looks like this:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run(); 

In .NET 6, Microsoft removed the Startup.cs file and put all the startup code in Program.cs.

There are a few things worthy of mentioning here. It starts with adding all the dependencies we need in our application. In this case, we add RazorPages, the pages that run Blazor (these are the .cshtml files). Then we add ServerSideBlazor, giving us access to all the objects we need to run Blazor Server. Then we add WeatherForcastService, which is used when you navigate to the Forecast page.

It also configures HTTP Strict Transport Security (HSTS), forcing your application to use HTTPS, and will make sure that your users don’t use any untrusted resources or certificates. We also ensure that the site redirects to HTTPS to secure the site.

UseStaticFiles enables downloading static files such as CSS or images.

The different Use* methods add request delegates to the request pipeline or middleware pipeline. Each request delegate (DeveloperException, httpRedirection, StaticFiles, and so on) is called consecutively from the top to the bottom and back again.

This is why the exception handler is the first one to be added.

If there is an exception in any of the request delegates that follow, the exception handler will still be able to handle it (since the request travels back through the pipeline), as shown in Figure 2.15:

Figure 2.15 – The request middleware pipeline

Figure 2.15: The request middleware pipeline

If any of these request delegates handle the request in the case of a static file, for example, there is no need to involve routing, and the remaining request delegates will not get called. There is no need to involve routing if the request is for a static file. Sometimes, it is essential to add the request delegated in the correct order.

NOTE:

There is more information about this here if you want to dig even further: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-7.0.

At the end of the class, we hook up routing and add endpoints. We create an endpoint for the Blazor SignalR hub, and if we don’t find anything to return, we make sure that we will call the _host file that will handle routing for the app. When _host has triggered, the first page of the app will get loaded.

Index/_Host

The next thing that happens is that the Index or _host file runs, and it contains the information to load the necessary JavaScript.

_Host (Blazor Server)

The Blazor Server project has a _Host.cshtml file that is located in the pages folder. It is a Razor page, which is not the same thing as a Razor component:

  • A Razor page is a way to create views or pages. It can use Razor syntax but not as a component (a component can be used as part of a page and inside of another component).
  • A Razor component is a way to build reusable views (called components) that you can use throughout your app. You can build a Grid component (for example, a component that renders a table) and use it in your app, or package it as a library for others to use. However, a component can be used as a page by adding an @ page directive to your component, and it can be called a page (more on that later).

For most Blazor Server applications, you should only have one .cshtml page; the rest should be Razor components.

At the top of the page, you will find some @ directives (such as page, namespace, and addTagHelper):

@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace BlazorServer.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head><component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
    <component type="typeof(App)" render-mode="ServerPrerendered" />

There are a couple of aspects of this file that are worth noting. The @ directives make sure to set the URL for the page, add a namespace, add a tag helper, and that we are using a Layout page. We will cover directives in Chapter 4, Understanding Basic Blazor Components.

Then we have the component tag:

<component type="typeof(App)" render-mode="ServerPrerendered" />

This is where the entire application will be rendered. The App component handles that. This is also how you would add a Blazor component to your existing non-Blazor app using the component tag helper.

It will render a component called App. There are five different render modes:

  • The first one is the default ServerPrerendered mode, which will render all the content on the server and deliver it as part of the content when the page gets downloaded for the first time. Then it will hook up the Blazor SignalR hub and make sure your changes will be pushed to and from the server; however, the server will make another render and push those changes over SignalR. Typically, you won’t notice anything, but if you are using certain events on the server, they may get triggered twice and make unnecessary database calls, for example.
  • The second option is Server, which will send over the whole page and add placeholders for the components. It then hooks up SignalR and lets the server send over the changes when it is done (when it has retrieved data from the database, for example).
  • The third option is Static, which will render the component and then disconnect, which means that it will not listen to events and won’t update the component any longer. This can be a good option for static data.
  • The fourth option is WebAssembly, which will render a marker for the WebAssembly application but not output anything from the component.
  • The fifth option is WebAssemblyPrerendered, which will render the component into static HTML and bootstrap the WebAssembly app into that space. We will explore this scenario in Chapter 5, Creating Advanced Blazor Components.

ServerPrerendered is technically the fastest way to get your page up on the screen; if you have a page that loads quickly, this is a good option. If you want your page to have a perceived fast loading time that shows you content fast and loads the data when the server gets the data from a database, then Server is a better option, in my opinion.

I prefer the Server option because the site should feel fast. Switching to Server is the first thing I change when creating a new Blazor Server site; I’d much rather have the data pop up a couple of milliseconds later because the page will feel like it loads faster.

Close to the top of the page, we have the base tag:

<base href="~/" />

The base tag allows Blazor to find the site’s root. Without the base tag, Blazor won’t be able to find any static resources like images, JavaScript, and CSS.

Then we have CSS. By default, there are two static CSS files, one for Bootstrap and one for the site.

<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="BlazorServer.styles.css" rel="stylesheet" />

There is also the one called BlazorServer.styles.css, a generated file with all the isolated CSS. CSS and Isolated CSS is something we will cover more in-depth in Chapter 9, Sharing Code and Resources.

We also have a component that gets rendered. This is the HeadOutlet component, which makes it possible to change the head metadata like the title and meta tags:

<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />

We will use this component in Chapter 5, Creating Advanced Blazor Components, to add metadata and change the title.

There is a small part of the UI that will show if there are any error messages:

<div id="blazor-error-ui">
    <environment include="Staging,Production">
        An error has occurred. This application may no longer respond until reloaded.
    </environment>
    <environment include="Development">
        An unhandled exception has occurred. See browser dev tools for details.
    </environment>
    <a href="" class="reload">Reload</a>
    <a class="dismiss"></a>
</div>

I would recommend keeping this error UI (or a variation) if we changed the layout completely because JavaScript is involved in updating the UI. Sometimes, your page may break, the JavaScript will stop running, and the SignalR connection will fail. You will get a nice error message in the JavaScript console if that happens. But by having the error UI pop up, you’ll know that you need to check the console.

The last thing we will cover on this page is also where all the magic happens, the JavaScript responsible for hooking everything up:

<script src="_framework/blazor.server.js"></script>

The script will create a SignalR connection to the server and is responsible for updating the DOM from the server and sending triggers back to the server.

Index (WebAssembly)

The WebAssembly project looks pretty much the same.

In the BlazorWebAssembly.Client project, open the wwwroot/index.html file. This file is HTML only, so there are no directives at the top like in the Blazor Server version.

Just like the Blazor Server version, you will find a base tag:

<base href="/" />

When hosting a Blazor WebAssembly site on, for example, GitHub Pages, we need to change the base tag to make the site work since it is served from a subfolder.

Instead of a component tag (as with Blazor Server), you’ll find a div tag here. Instead, there was a line in Program.cs that connects the App component to the div tag (see the previous Program.cs section):

<div id="app">Loading...</div>

You can replace Loading... with something else if you want to – this is the content shown while the app is starting.

The error UI looks a bit different as well. There is no difference between development and production as in Blazor Server. Here, you only have one way of displaying errors:

<div id="blazor-error-UI">
    An unhandled error has occurred.
    <a href="" class="reload">Reload</a>
    <a class="dismiss"></a>
</div>

Lastly, we have a script tag that loads JavaScript. This makes sure to load all the code needed for the WebAssembly code to run:

<script src="_framework/blazor.webassembly.js"></script>

Like how the Blazor Server script communicates with the backend server and the DOM, the WebAssembly script communicates between the WebAssembly .NET runtime and the DOM.

At this point, the app is starting up running the Razor component. These components are the same in both projects.

App

The App component is the same for both Blazor WebAssembly and Blazor Server. It contains a Router component:

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

This file handles the routing, finding the suitable component to show (based on the @page directive). It shows an error message if the route can’t be found. In Chapter 8, Authentication and Authorization, we will make changes to this file when we implement authentication.

The App component also includes a default layout. We can override the layout per component, but usually, you’ll have one layout page for your site. In this case, the default layout is called MainLayout.

MainLayout

MainLayout contains the default layout for all components when viewed as a page. The MainLayout contains a couple of div tags, one for the sidebar and one for the main content:

@inherits LayoutComponentBase
<PageTitle>BlazorServer</PageTitle>
<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>
    <main>
        <div class="top-row px-4">
            <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
        </div>
        <article class="content px-4">
            @Body
        </article>
    </main>
</div>

The only things you need in this document are @inherits LayoutComponentBase and @Body; the rest is just Bootstrap. The @inherits directive inherits from LayoutComponentBase, which contains all the code to use a layout. @Body is where the component will be rendered (when viewed as a page).

Bootstrap

Bootstrap is one of the most popular CSS frameworks for developing responsive and mobile-first websites.

We can find a reference to Bootstrap in the wwwroot/index.html file.

It was created by and for Twitter. You can read more about Bootstrap here: https://getbootstrap.com/.

At the top of the layout, you can see <NavMenu>, a Razor component. It is located in the Shared folder and looks like this:

<div class="top-row ps-3 navbar navbar-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="">BlazorServer</a>
        <button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
</div>
<div class="@NavMenuCssClass nav-scrollable" @onclick="ToggleNavMenu">
    <nav class="flex-column">
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                <span class="oi oi-home" aria-hidden="true"></span> Home
            </NavLink>
        </div>
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="counter">
                <span class="oi oi-plus" aria-hidden="true"></span> Counter
            </NavLink>
        </div>
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
            </NavLink>
        </div>
    </nav>
</div>
@code {
    private bool collapseNavMenu = true;
    private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null;
    private void ToggleNavMenu()
    {
        collapseNavMenu = !collapseNavMenu;
    }
}

It contains the left-side menu and is a standard Bootstrap menu. It also has three menu items and logic for a hamburger menu (if viewed on a phone). This type of nav menu is usually done with JavaScript, but this one is done solely with CSS and C#.

You will find another component, NavLink, which is built into the framework. It will render an anchor tag but will also check the current route. If you are currently on the same route/URL as the nav link, it will automatically add a CSS class called active to the tag.

We will run into a couple more built-in components that will help us along the way. There are also some pages in the template, but we will leave them for now and go through them in the next chapter when we go into components.

CSS

In the Shared folder, there are two CSS files as well : NavMenu.razor.css and MainLayout.razor.css.

These files are CSS styles that affect only the specific component (the first part of the name). We will return to a concept called isolated CSS in Chapter 9, Sharing Code and Resources.

Summary

In this chapter, we got the development environment up and running, and we created our first Blazor app for both Blazor WebAssembly and Blazor Server. You learned in what order classes, components, and layouts are called, making it easier to follow the code. We also covered some differences between a Blazor Server project and a Blazor WebAssembly project.

In the next chapter, we will take a break from Blazor to look at managing state and set up a repository to store our blog posts.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create a production-ready Blazor application from start to finish
  • Learn Blazor fundamentals, gain actionable insights, and discover best practices
  • Find out how, when, and why to use Blazor Server and Blazor WebAssembly, as well as Blazor Hybrid

Description

Blazor is an essential tool if you want to build interactive web apps without JavaScript, but it has a learning curve. Updated with the latest code in .NET 7 and C# 11 and written by someone who adopted Blazor early, this book will help you overcome the challenges associated with being a beginner with Blazor and teach you the best coding practices. You’ll start by learning how to leverage the power of Blazor and exploring the full capabilities of both Blazor Server and Blazor WebAssembly. Then you'll move on to the practical part, centered around a sample project – a blog engine. You'll apply all your newfound knowledge about creating Blazor projects, the inner workings of Razor syntax, validating forms, and creating your own components. This new edition also looks at source generators, dives deeper into Blazor WebAssembly with ahead-of-time, and includes a dedicated new chapter demonstrating how to move components of an existing JavaScript (Angular, React) or MVC-based website to Blazor or combine the two. You’ll also see how to use Blazor (Hybrid) together with .NET MAUI to create cross-platform desktop and mobile applications. When you reach the end of this book, you'll have the confidence you need to create and deploy production-ready Blazor applications, and you'll have a big-picture view of the Blazor landscape.

What you will learn

Understand the different technologies that can be used with Blazor, such as Blazor Server, Blazor WebAssembly, and Blazor Hybrid Find out how to build simple and advanced Blazor components Explore the differences between Blazor Server and Blazor WebAssembly projects Discover how Minimal APIs work and build your own API Explore existing JavaScript libraries in Blazor and JavaScript interoperability Learn techniques to debug your Blazor Server and Blazor WebAssembly applications Test Blazor components using bUnit

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Mar 16, 2023
Length 360 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781803241494
Vendor :
Microsoft
Category :

Table of Contents

22 Chapters
Preface Chevron down icon Chevron up icon
Hello Blazor Chevron down icon Chevron up icon
Creating Your First Blazor App Chevron down icon Chevron up icon
Managing State – Part 1 Chevron down icon Chevron up icon
Understanding Basic Blazor Components Chevron down icon Chevron up icon
Creating Advanced Blazor Components Chevron down icon Chevron up icon
Building Forms with Validation Chevron down icon Chevron up icon
Creating an API Chevron down icon Chevron up icon
Authentication and Authorization Chevron down icon Chevron up icon
Sharing Code and Resources Chevron down icon Chevron up icon
JavaScript Interop Chevron down icon Chevron up icon
Managing State – Part 2 Chevron down icon Chevron up icon
Debugging the Code Chevron down icon Chevron up icon
Testing Chevron down icon Chevron up icon
Deploy to Production Chevron down icon Chevron up icon
Moving from, or Combining, an Existing Site Chevron down icon Chevron up icon
Going Deeper into WebAssembly Chevron down icon Chevron up icon
Examining Source Generators Chevron down icon Chevron up icon
Visiting .NET MAUI Chevron down icon Chevron up icon
Where to Go from Here Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(1 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


Anton Jan 23, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I like that the book quickly moves beyond simple cases and starts to build a set of projects that one can expect for a non-trivial project with long-term maintenance requirements. The biggest drawback of the book is that some of its discussions of key concepts are not applicable for .NET8, the current version.
Feefo Verified review Feefo image
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.