Book Image

Mastering Blazor WebAssembly

By : Ahmad Mozaffar
3.5 (2)
Book Image

Mastering Blazor WebAssembly

3.5 (2)
By: Ahmad Mozaffar

Overview of this book

Blazor WebAssembly is a revolutionary technology in software development that enables you to develop web applications with a rich user interface using C# without JavaScript. It can be run natively in the browser and soon on mobile apps with .NET MAUI, making it a superweapon in the .NET developer’s toolbox. This capability has opened the doors for the JavaScript community to have a stable framework to build single page applications (SPAs) maintained by Microsoft and driven by the community. Mastering Blazor WebAssembly is a complete resource that teaches you everything you need to build client-side web applications using C# & .NET 7.0. Throughout this book, you’ll discover the anatomy of a Blazor WebAssembly project, along with the build, style, and structure of the components. You’ll implement forms to catch user input and collect data, as well as explore the topics of navigating between the pages in depth. The chapters will guide you through handling complex scenarios like RenderTrees, writing efficient unit tests, using variant security methods, and publishing the app to different providers, all in a practical manner. By the end of this book, you’ll have the skills necessary to build web apps with Blazor WebAssembly, along with the basics for a future in mobile development with .NET MAUI and Blazor.
Table of Contents (21 chapters)
1
Part 1: Blazor WebAssembly Essentials
5
Part 2: App Parts and Features
13
Part 3: Optimization and Deployment

Discovering the project structure

Now we have a workspace that we can use to start building our application, but before we dive in deeper, let’s take a look at the structure of the project, including the files and folders we see. Understanding the what and why of each file in Solution Explorer is key to completing the project we will be building.

Let’s start exploring!

The wwwroot folder

The wwwroot folder is considered the root folder of your project. Root, here, doesn’t mean the root in your file explorer, which is the one that contains the Razor files and other folders. wwwroot is the place where your app's static files, including global CSS styles, the main HTML file of the project, index.html, JavaScript, and assets (images, icons, static documents, etc.), live. It’s also where you put the JSON files that represent the configuration of your app (you will read more about configuration in the next section of this chapter, Dependency injection in Blazor WebAssembly).

By default, the wwwroot folder contains the following:

  • The css folder: This folder comes with Bootstrap CSS files and the default font. The folder also includes the app.css file, which carries the global styles of the app.
  • The sample-data folder: This folder contains a JSON file with sample data pertaining to a weather forecast. This is used as a data source for the Fetch data page, which will be mentioned soon.
  • favicon.ico: This refers to the default icon of the app that you see at the top left of the browser tab of your application, in the favorite sites list in the browser, and in some other places.
  • Icon-192.png: This is the Blazor icon PNG file that’s referenced in the components.
  • index.html: The name of this file should be familiar to you. Most of the time, index.html is the default HTML file that will be opened when we access a static website. This main HTML file contains our app. The browser downloads this file and opens it with all its references from CSS and JavaScript, most importantly blazor.webassembly.js.

The body of index.html contains, by default, a div with the ID app (this is basically where all the UI that you see in any Blazor app resides), and another div with the ID blazor-error-ui, which is a simple design div that shows up when an unhandled exception occurs (you will learn more about this in Chapter 10, Handling Errors in Blazor WebAssembly).

While developing your apps, you are going to make changes to this file mostly to add style references or some JavaScript files later in this book.

The following is the code for the default body elements (app div and blazor-error-ui div) within the index.html file:

<html lang="en">….
<body>
    <div id="app">Loading...</div>
    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>
    <script
      src="_framework/blazor.webassembly.js"></script>
</body>
</html>

Note

The term Single-Page Application (SPA) seems a bit weird when you open the app and start navigating from one page to another. However, technically SPAs consist of a single HTML page and Blazor or any other JavaScript framework (ReactJS, Angular, etc.) dynamically updates the content of that page. As you have seen, in the wwwroot folder, there is only one HTML page in our whole application, called index.html.

The Pages folder

Pages is the default folder where Microsoft puts its default pages that come with the template. You can use Pages as the container for your app’s page components. However, it’s not mandatory to put your components in this folder and you can even delete it. Pages comes with three sample pages that cover different concepts, such as calling a shared component, updating the DOM using a button, and fetching data from a data source:

  • Counter.razor: This is a Razor component that you can access through the route /counter. This is also an example of calling a C# method from an HTML button and binding an HTML <p> element’s content to a C# variable to show the result.
  • FetchData.razor: You can access this component by navigating to /fetch-data. This page contains an HTML table that shows weather forecast data and demonstrates how to fetch data using the HttpClient. By injecting the object and making an HTTP GET request to grab the JSON data from the weather.json file in the wwwroot folder, the data is rendered within the component.
  • Index.razor: This is the default component that you will see when you run the project. It shows you how to call other shared components such as SurveryPrompt and pass the Title parameter to it.

The Shared folder

As the name indicates, this folder holds some shared components across the app. You can override this structure, but we are going to follow the same structure through the rest of this book and will use this folder to contain the components that will be shared across all the pages (app layout, nav menu, authentication components, etc.). By default, the Blazor template comes with three shared components:

  • MainLayout.razor: This comprises the default layout of the project and is a special kind of component. It defines what the app looks like and allocates the content components (pages) to the right place.

By default, this component references the NavMenu component and contains a <main> HTML tag that renders the @Body property. This property holds the content of the pages based on the navigated route (more about layout components will be covered in Chapter 3, Developing Advanced Components in Blazor).

  • NavMenu.razor: This component contains the menu items of the app (a set of URLs to navigate between the pages mentioned in the Pages folder).
  • SuveryPrompt.razor: This is a simple component to demonstrate how to create a reusable component that accepts parameters. The Index page references this component and passes a value for its Title parameter.

The _Imports.razor file

In C# classes, you always need to use classes existing in different namespaces. So, basically, we reference a namespace by declaring a using statement at the top of the C# file so we can reference the required classes and nested namespaces. The _Imports.razor file is there for this purpose, and you can use it to reference common namespaces across the majority of your components. So, there is no need to add a using statement at the top of each Razor file to access the required code. By default, the component references some common .NET namespaces that you will use across your components, such as System.Net.Http and the namespace of your assembly and the shared folder.

The following is the code for the _imports.razor file with the shared referenced namespaces:

@using System.Net.Http…
@using Microsoft.JSInterop
@using BooksStore
@using BooksStore.Shared

The App.razor file

The App component is the parent and the main component of the Blazor app. It basically defines the infrastructure required for your application to function, such as the Router component, which matches the URL entered in the browser and renders the associated component in your app. The App component also defines the default layout component (MainLayout, mentioned in the Shared folder). More about layout components will be covered in Part 2, Chapter 3, Developing Advanced Components in Blazor. Further, the App component contains the NotFound section, which you can use to render specific content if the requested address was not found.

The Program.cs file

In any C# application, there is an entry point and Program.cs represents the entry point of your Blazor app. This entry point sets up the Blazor WebAssembly host and maps the App component to the corresponding div within the index.html file (by default, the div with the ID app). We also use the file to register any service that we need to use throughout the application’s lifetime in the DI container.

Now you should be able to navigate easily within the solution after understanding what every file does and why it’s there; the next step in this chapter is looking at the concept of DI.