Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Web Development with Blazor
Web Development with Blazor

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

eBook
€28.99 €41.99
Paperback
€52.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Web Development with Blazor

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.

Who is this book for?

This book is for .NET web developers and software developers who want to use their existing C# skills to build interactive SPA applications running either inside the web browser using Blazor WebAssembly, or on the server using Blazor Server. You’ll need intermediate-level web-development skills, basic knowledge of C#, and prior exposure to .NET web development before you get started; the book will guide you through the rest.

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

Product Details

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

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 135.97
Web Development with Blazor
€52.99
Apps and Services with .NET 8
€37.99
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
€44.99
Total 135.97 Stars icon
Banner background image

Table of Contents

21 Chapters
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

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(19 Ratings)
5 star 68.4%
4 star 10.5%
3 star 10.5%
2 star 10.5%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Troy Martin Mar 22, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Background - I'm a self-taught programmer of 8+ years in various frameworks/engines/languages, mostly sticking with C# but fluent in many other notable languages. I suppose I'd be considered a life-long learner. I've recently been diving into web development to create a project I've been tossing around in my brain for a few months and have been consuming many books the last several months.This is the easiest 5 Star review I've given to a book for the last 6 months or so and has been added to my top 10 list of "Books You Need to own".With all that in mind, this is simply a must-have to ANYONE who is interested in web development and/or the Blazor framework. The book goes through everything you need to know to make your own web site from the very beginnings of a project and, throughout the book, construct a fully-functioning blog website ending in deployment and even tips on how to move from an existing site to Blazor.The first chapter explains Blazor in depth, including the differences between Server and Web Assembly, explaining how each one operates and even went so far as to creating a chart showing the differences in download size for single-page applications from large companies in comparison to a blazor sample setup.The second chapter gets into the creation of a new project. Everything is well documented and should leave no questions. There's SO much additional information here than what I am accustomed to when reading similar 'project creation' chapters from past books. It demonstrates the use of using the developer console through a browser to review file size transfer speeds, explaining EXACTLY what files are being sent and why. There's also CLI options Jimmy explains, which was much appreciated for me, being a Linux user. He then goes through each file created by a new project and covers exactly what each file does.From here on out, each chapter will introduce new concepts and you continue to build upon a blog web site using both Blazor Web Assembly and Server. Most notably are the chapters on Razor, two chapters on Blazor's component system, diving far into depth with all the features available to this, validation and forms (complete with admin panel), authentication, and so much more.Later chapters go way above and beyond what I would expect. It goes into advanced topics like browser storage, using a javascript interop to not only read js code in, but even go from .NET to JS or JS to .NET.Basically, I came into this book with the expectation I would use Blazor to build a blog page. What I WASN'T expecting was the amount of depth Jimmy goes into with exactly how everything works and why you would want to use it. Sprinkled through this read was things I didn't even know possible and it opens the door to a lot more experimentation / research.Buy this. You won't be disappointed.
Amazon Verified review Amazon
Imad Ayoub May 21, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
7 stars book for blazor developers. From zero to hero. Thanks a lot for the auditor.
Amazon Verified review Amazon
A. Zubarev May 01, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
In short, this is a book written by an expert for a future expert.After having read and practised the Blazor WebAssembly by Example by Toi B. Wright (which is a fine book in its own right) I wanted to continue on the learning path and decided to look into Web Development with Blazor.This book added a lot to my general knowledge where Blazor WebAssembly by Example left several common topics untouched, but excelled in covering creations of many typical applications and Blazor usage cases.It felt right away that the author of Web Development with Blazor is an advanced web developer, and as a bonus I liked the author's writing style, occasional humour and advice.Again, as oppose to how is the Blazor WebAssembly by Example is done, this book, instead of covering multiple projects, goes through only one - building a blog hosting engine. But covers it comprehensively and it resembles a monotonous typical developer's work on a large project, and is being done in an iterative manner with the end result having a complete product built.The other tidbit is a list of technical requirements at the beginning of each chapter which I find being nice to have to ensure one can complete it.The styling of the app is covered very well and I know that every project requires a lot of attention to.Besides, the JavaScript interop is thoroughly covered - this is especially valuable for those who are relatively new to the web development.Lastly, I can only think of one improvement: I wish the debugging part would come much earlier in the book.If you want to master Blazor - this is your book.
Amazon Verified review Amazon
Notchy Mar 16, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a well-written guide on Blazor Development. It assumes no prior knowledge and steadily goes from level to level with each new chapter, exploring the ins and outs of Blazor development.I recommend.
Amazon Verified review Amazon
Sarbjit Singh Hanjra Apr 28, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"Web Development with Blazor" by Jimmy Engström published by Packt is an exceptional resource for anyone interested in learning how to develop web applications using Blazor, a cutting-edge technology that allows developers to build web apps using C# and .NET. This book covers all the essential topics, starting from the fundamentals of Blazor and gradually progressing towards more advanced concepts like Blazor components, validation, authentication, Managing State, testing, and deployment. The author's writing style is both clear and concise, providing an easy-to-follow guide throughout the book. Additionally, code examples are presented with accompanying screenshots, making it easier for readers to understand and implement the concepts. In summary, this book is highly recommended for developers who want to stay up-to-date with modern technologies like Blazor and .NET and build innovative web applications.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.