Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Blazor WebAssembly by Example
Blazor WebAssembly by Example

Blazor WebAssembly by Example: A project-based guide to building web apps with .NET, Blazor WebAssembly, and C#

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

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
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Blazor WebAssembly by Example

Chapter 2: Building Your First Blazor WebAssembly Application

Razor components are the building blocks of Blazor WebAssembly applications. A Razor component is a chunk of user interface that can be shared, nested, and reused. Razor components are ordinary C# classes and can be placed anywhere in a project.

In this chapter, we will learn about Razor components. We will learn how to use them, how to apply parameters, and about their life cycle and their structure. We will learn how to use the @page directive to define routing. We will also learn how to use Razor syntax to combine C# code with HTML markup.

The Blazor WebAssembly project in this chapter will be created by using the Blazor WebAssembly App project template provided by Microsoft. After we create the project, we will examine it to further familiarize ourselves with Razor components. We will learn how to use components, how to add parameters, how to apply routing, how to use Razor syntax, and how to separate the Razor markup and code into separate files. Finally, we will configure our own custom project template that creates an empty Blazor WebAssembly project.

In this chapter, we will cover the following topics:

  • Razor components
  • Routing
  • Razor syntax
  • Using the Blazor App project template
  • Creating an empty Blazor WebAssembly project template

Technical requirements

To complete this project, you need to have Visual Studio 2019 installed on your PC. For instructions on how to install the free Community edition of Visual Studio 2019, refer to Chapter 1, Introduction to Blazor WebAssembly.

The source code for this chapter is available in the following GitHub repository: https://github.com/PacktPublishing/Blazor-WebAssembly-by-Example/tree/main/Chapter02.

The code in action video is available here: https://bit.ly/3bEZrrg.

Razor components

Blazor WebAssembly is a component-driven framework. Razor components are the fundamental building blocks of a Blazor WebAssembly application. They are classes that are implemented using a combination of C#, HTML, and Razor markup. When the web app loads, the classes get downloaded into the browser as normal .NET assemblies (DLLs).

Important note

In this book, the terms Razor component and component are used interchangeably.

Using components

HTML element syntax is used to add a component to another component. The markup looks like an HTML tag where the name of the tag is the component type.

The following markup in the Pages\Index.razor file of the Demo project that we will create in this chapter will render a SurveyPrompt instance:

<SurveyPrompt Title="How is Blazor working for you?" />

The preceding SurveyPrompt element includes an attribute parameter named Title.

Parameters

Component parameters are used to make components dynamic. Parameters are public properties of the component that are decorated with either the Parameter attribute or the CascadingParameter attribute. Parameters can be simple types, complex types, functions, RenderFragments, or event callbacks.

The following code for a component named HelloWorld includes a parameter named Text:

HelloWorld.razor

<h1>Hello @Text!</h1>
@code {
    [Parameter] public string Text { get; set; }
}

To use the HelloWorld component, include the following HTML syntax in another component:

<HelloWorld Text="World" />

In the preceding example, the Text attribute of the HelloWorld component is the source of the Text parameter. This screenshot shows the results of using the component as indicated:

Figure 2.1 – HelloWorld component

Figure 2.1 – HelloWorld component

A component can also receive parameters from its route or a query string. You will learn more about the different types of parameters later in this chapter.

Naming components

The name of a Razor component must be in title case. Therefore, helloWorld would not be a valid name for a Razor component since the h is not capitalized. Also, Razor components use the RAZOR extension rather than the CSHTML extension that is used by Razor Pages.

Important note

Razor components must start with a capital letter.

Component life cycle

Razor components inherit from the ComponentBase class. The ComponentBase class includes both asynchronous and synchronous methods used to manage the life cycle of a component. In this book, we will be using the asynchronous versions of the methods since they execute without blocking other operations. This is the order in which the methods in the life cycle of a component are invoked:

  1. SetParameterAsync: This method sets the parameters that are supplied by the component's parent in the render tree.
  2. OnInitializedAsync: This method is invoked after the component is first rendered.
  3. OnParametersSetAsync: This method is invoked after the component initializes and each time the component re-renders.
  4. OnAfterRenderAsync: This method is invoked after the component has finished rendering. This method is for working with JavaScript since JavaScript requires the Document Object Model (DOM) elements to be rendered before they can do any work.

Component structure

The following diagram shows code from the Counter component of the Demo project that we will create in this chapter:

Figure 2.2 – Component structure

Figure 2.2 – Component structure

The code in the preceding example is divided into three sections:

  • Directives
  • Markup
  • Code Block

Each of the sections has a different purpose.

Directives

Directives are used to add special functionality, such as routing, layout, and dependency injection. They are defined within Razor and you cannot define your own directives.

In the preceding example, there is only one directive used – the @page directive. The @page directive is used for routing. In this example, the following URL will route the user to the Counter component:

/counter

A typical page can include many directives at the top of the page. Also, many pages have more than one @page directive.

Most of the directives in Razor can be used in a Blazor WebAssembly application. These are the Razor directives that are used in Blazor, in alphabetical order:

  • @attribute: This directive adds a class-level attribute to the component. The following example adds the [Authorize] attribute:

    @attribute [Authorize]

  • @code: This directive adds class members to the component. In the example, it is used to distinguish the code block.
  • @implements: This directive implements the specified class.
  • @inherits: This directive provides full control of the class that the view inherits.
  • @inject: This directive is used for dependency injection. It enables the component to inject a service from the dependency injection container into the view. The following example injects HttpClient defined in the Program.cs file into the component:

    @inject HttpClient Http

  • @layout: This directive is used to specify a layout for the Razor component.
  • @namespace: This directive sets the component's namespace. You only need to use this directive if you do not want to use the default namespace for the component. The default namespace is based on the location of the component.
  • @page: This directive is used for routing.
  • @typeparam: This directive sets a type parameter for the component.
  • @using: This directive controls the components that are in scope.

Markup

This is HTML with Razor syntax. The Razor syntax can be used to render text and allows C# to be used as part of the markup. We will cover more about Razor syntax later in this chapter.

Code block

The code block contains the logic for the page. It begins with the @code directive. By convention, the @code directive is at the bottom of the page. It is the only file-level directive that is not placed at the top of the page.

The code block is where we add C# fields, properties, and methods to the component. Later in this chapter, we will move the code block to a separate code-behind file.

Razor components are the building blocks of a Blazor WebAssembly application. They are easy to use since they are simply a combination of HTML markup and C# code. In the next section, we will see how routing is used to navigate between each of the components.

Routing in Blazor WebAssembly

In Blazor WebAssembly, routing is handled on the client, not on the server. As you navigate in the browser, Blazor intercepts that navigation and renders the component with the matching route.

The URLs are resolved relative to the base path that is specified in the wwwroot/index.html file. It is specified in the head element using the following syntax:

 <base href="/" />

Unlike other frameworks that you may have used, the route is not inferred from the location of its file. For example, in the Demo project, the Counter component is in the /Pages/Counter folder, yet it uses the following route:

@page "/counter"

Route parameters

The Router component uses route parameters to populate the parameters of the corresponding component. The parameters of both the component and the route must have the same name, but they are not case sensitive.

Since optional route parameters are not supported, you may need to provide more than one @page directive to a component to simulate optional parameters. The following example shows how to include multiple @page parameters:

RoutingExample.razor

@page "/routing"
@page "/routing/{text}"
<h1>Blazor WebAssembly is @Text!</h1>
@code {
    [Parameter] public string Text { get; set; }
    protected override void OnInitialized()
    {
        Text = Text ?? "fantastic";
    }
}

In the preceding code, the first @page directive allows navigation to the component without a parameter and the second @page directive allows a route parameter. If a value for text is provided, it is assigned to the Text property of the component. If the Text property of the component is null, it is set to fantastic.

The following URL will route the user to the RoutingExample component:

/routing

The following URL will also route the user to the RoutingExample component, but this time the Text parameter will be set by the route:

/routing/amazing

This screenshot shows the results of using the indicated route:

Figure 2.3 – RoutingExample component

Figure 2.3 – RoutingExample component

Important note

Route parameters are not case sensitive.

Catch-all route parameters

Catch-all route parameters are used to capture paths across multiple folder boundaries. This type of route parameter is a string type and can only be placed at the end of the URL.

This is a sample component that uses a catch-all route parameter:

CatchAll.razor

@page "/{*path}"
<h1>Catch All</h1>
Route: @Path
@code {
    [Parameter] public string Path { get; set; }
}

For the /error/type/3 URL, the preceding code will set the value of the Path parameter to error/type/3:

Figure 2.4 – Catch-all route parameter example

Figure 2.4 – Catch-all route parameter example

Route constraints

Route constraints are used to enforce the datatype of a route parameter. To define a constraint, add a colon followed by the constraint type to the parameter. In the following example, the route is expecting a route parameter named Increment with the type of int:

@page "/counter/{increment:int}"

The following route constraints are supported:

Figure 2.5 – Supported route constraints

Figure 2.5 – Supported route constraints

The following types are not currently supported as constraints:

  • Regular expressions
  • Enums
  • Custom constraints

Routing is handled on the client. We can use both route parameters and catch-all route parameters to enable routing. Route constraints are used to ensure that a route parameter is of the required datatype. Razor components use Razor syntax to seamlessly merge HTML with C# code, which is what we will see in the next section.

Razor syntax

Razor syntax is made up of HTML, Razor markup, and C#. Rendering HTML from a Razor component is the same as rendering HTML from an HTML file. The HTML in a Razor component is rendered by the server unchanged. Razor syntax uses both inline expressions and control structures.

Inline expressions

Inline expressions start with an @ symbol followed by a variable or function name. This is an example of an inline expression:

<h1>Blazor is @Text!</h1>

Control structures

Control structures also start with an @ symbol. The content within the curly brackets is evaluated and rendered to the output. This is an example of an if statement from the FetchData component in the Demo project:

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}

Each code statement within a Razor code block must end with a semicolon. C# code is case sensitive and strings must be enclosed in quotation marks.

Conditionals

The following types of conditionals are included in Razor syntax:

  • if statements
  • switch statements

This is an example of an if statement:

@if (DateTime.Now.DayOfWeek.ToString() != "Friday")
{
    <p>Today is not Friday.</p>
}
else if (DateTime.Now.Day != 13)
{
    <p>Today is not the 13th.</p>
}
else
{
    <p>Today is Friday the 13th.</p>
}

The preceding code uses an if statement to check it the current day of the week is Friday and/or the current day of the month is the 13th.

This is an example of a switch statement:

@switch (value)
{
    case 1:
        <p>The value is 1!</p>
        break;
    case 42:
        <p>Your number is 42!</p>
        break;
    default:
        <p>Your number was not 1 or 42.</p>
        break;
}
@code {
    private int value = 2;
}

The preceding switch statement compares the value variable to 1 and 42.

Loops

The following types of loops are included in Razor syntax:

  • for loops
  • foreach loops
  • while loops
  • do while loops

Each of the following examples uses an array of the WeatherForecast type. WeatherForecast includes a Summary property and is defined in the Demo project.

This is an example of a for loop:

@for (var i = 0; i < forecasts.Count(); i++)
{
   <div> forecasts[i].Summary</div>
};
@code {
    private WeatherForecast[] forecasts;
}

This is an example of a foreach loop:

@foreach (var forecast in forecasts)
{
    <div>@forecast.Summary</div>
};
@code {
    private WeatherForecast[] forecasts;
}

This is an example of a while loop:

@while (i < forecasts.Count())
{
    <div>@forecasts[i].Summary</div>
    i++;
};
@code {
    private WeatherForecast[] forecasts;
    private int i = 0;
}

This is an example of a do while loop:

@do
{
    <div>@forecasts[i].Summary</div>
    i++;
} while (i < forecasts.Count());
@code {
    private WeatherForecast[] forecasts;
    private int i = 0;
}

Razor syntax is easy to learn if you already know C#. It includes both inline expressions and control structures such as conditionals and loops.

Project overview

The Blazor WebAssembly application that we are going to build in this chapter is a simple three-page application. Each page will be used to demonstrate one or more features of Razor components.

This is a screenshot of the completed Demo project:

Figure 2.6 – Home page of the Demo project

Figure 2.6 – Home page of the Demo project

After we have completed the Demo project, we will convert it into an empty Blazor WebAssembly project. The empty Blazor WebAssembly project will be used as the basis for a custom Blazor WebAssembly App project template.

Creating the Demo Blazor WebAssembly project

The Demo project that we are creating is based on one of the many sample projects that are provided by the Blazor WebAssembly App project template. After we have used the template to create the project, we will examine the files in the sample project and update some of the files to demonstrate how to use Razor components. Finally, we will separate the code block of one of the components into a separate file to demonstrate how to use the code-behind technique to separate the markup from the code.

Creating the Demo project

Visual Studio comes with quite a few project templates. We are going to use the Blazor WebAssembly App project template to create our first Blazor WebAssembly project. Since this project template can be used to create many different types of Blazor projects, it is important to follow the instructions carefully:

  1. Open Visual Studio 2019.
  2. Click the Create a new project button.
  3. In the Search for templates (Alt+S) textbox, enter Blazor and hit the Enter key.

    The following screenshot shows the Blazor WebAssembly App project template that we will be using:

    Figure 2.7 – Blazor WebAssembly App project template

    Figure 2.7 – Blazor WebAssembly App project template

  4. Select the Blazor WebAssembly App project template and click the Next button.
  5. Enter Demo in the Project name textbox and click the Next button.

    This is a screenshot of the dialog used to configure our new project:

    Figure 2.8 – The Configure your new project dialog

    Figure 2.8 – The Configure your new project dialog

    Tip

    In the preceding example, we placed the Demo project into the E:\Blazor folder. However, the location of this project is not important.

  6. Select .NET 5.0 as the version of the .NET Framework to use.

    This is a screenshot of the dialog used to create our new Blazor WebAssembly app:

    Figure 2.9 – Additional information for the Blazor WebAssembly App dialog

    Figure 2.9 – Additional information for the Blazor WebAssembly App dialog

  7. Click the Create button.

You have created the Demo Blazor WebAssembly project.

Running the Demo project

Once the project has been created, you need to run it to get an understanding of what it does. The Demo project contains three pages: Home, Counter, and Fetch data:

  1. From the Debug menu, select the Start Without Debugging (Ctrl+F5) option to run the Demo project.

    This is a screenshot of the Home page from the Demo project:

    Figure 2.10 – The Home page

    Figure 2.10 – The Home page

    The Home page is split into two sections. The navigation menu is on the left side of the page and the body is on the right side of the page. The body of the Home page consists of some static text and a link to a survey.

  2. Click the Counter option on the navigation menu to navigate to the Counter page.

    This is a screenshot of the Counter page from the Demo project:

    Figure 2.11 – The Counter page

    Figure 2.11 – The Counter page

    The body of the Counter page includes a counter and a Click me button. Each time the button on the Counter page is clicked, the counter is incremented without a page refresh.

    Important note

    Since this is a Single-Page Application (SPA), only the section of the page that needs to be updated is updated.

  3. Click the Fetch data option on the navigation menu to navigate to the Fetch data page.

    This is a screenshot of the Fetch data page from the Demo project:

Figure 2.12 – The Fetch data page

Figure 2.12 – The Fetch data page

The body of the Fetch data page includes a table that shows the weather forecast for a few days in 2018. As you will see, the data displayed in the table is static data from the wwwroot\sample-data\weather.json file.

Examining the Demo project's structure

Now let's return to Visual Studio to examine the files in the Demo project.

The following figure shows the project's structure:

Figure 2.13 – Project structure

Figure 2.13 – Project structure

The project includes quite a few files with some of them divided into their own folders. Let's examine them.

The wwwroot folder

The wwwroot folder is the application's web root. Only the files in this folder are web-addressable. The wwwroot folder contains a collection of Cascading Style Sheets (CSS) files, a sample data file, an icon file, and index.html. Later in this book, in addition to these types of files, we will use this folder for public static resources such as images and JavaScript files.

The index.html file is the root page of the web application. Whenever a page is initially requested, the contents of the index.html page are rendered and returned in the response. The head element of the index.html file includes links to each of the CSS files in the css folder and specifies the base path to use for the web app. The body element of the index.html file includes two div elements and a reference to the blazor.webassembly.js file.

This is the code in the body element of the index.html file:

<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">x</a>
    </div>
    <script 
      src="_framework/blazor.webassembly.js"></script>
</body>

The highlighted div element in the preceding code loads the App component.

The blazor-error-ui div element is for displaying unhandled exceptions. The styling for this div element is in the wwwroot\css\app.css file. The blazor.webassembly.js file is the script that downloads the .NET runtime, your application's assemblies, and your application's dependencies. It also initializes the runtime to run the web app.

The App component

The App component is defined in the App.razor file:

App.razor

<Router AppAssembly="@typeof(Program).Assembly" 
        PreferExactMatches="@true">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" 
                   DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

The App component is the root component of a Blazor WebAssembly application. It uses the Router component to set up the routing for the web app. In the preceding code, if the route is found, the RouteView component receives RouteData and renders the specified component using the indicated DefaultLayout. If the route is not found, the NotFound template is used and LayoutView is rendered using the indicated Layout.

As you can see, in the Demo project, both the Found template and the NotFound template are using the same layout. They are both using the MainLayout component. However, they do not need to use the same layout component.

The Shared folder

The Shared folder in the Demo project includes the shared user interface Razor components, including the MainLayout component. Each of these components may be used one or more times by other Razor components.

The Pages folder

The Pages folder includes the routable Razor components used by the project. The routable components are Counter, FetchData, and Index. Each of these components includes an @page directive that is used to route the user to the page.

The _Imports.razor file

This file includes Razor directives such as the @using directive for namespaces. Your project can include multiple _Imports.razor files. Each one is applied to its current folder and subfolders. Any @using directives in the _Imports.razor file are only applied to Razor (RAZOR) files. They are not applied to C# (CS) files. This distinction is important when using the code-behind technique.

The Program.cs file

The Program.cs file is the entry point for the application.

Examining the shared Razor components

The shared Razor components are in the Shared folder. There are three shared Razor components in the Demo project:

  • The MainLayout component
  • The NavMenu component
  • The SurveyPrompt component

The MainLayout component

The MainLayout component is used to define the page layout for the web app:

Pages/MainLayout.razor

@inherits LayoutComponentBase
<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>
    <div class="main">
        <div class="top-row px-4">
            <a href="http://blazor.net" 
               target="_blank" 
               class="ml-md-auto">About</a>
        </div>
        <div class="content px-4">
            @Body
        </div>
    </div>
</div>

The MainLayout component inherits from the LayoutComponentBase class. LayoutComponentBase represents a layout and has only one property, which is the Body property. The Body property gets the content to be rendered inside the layout.

The following diagram illustrates the layout of a page as defined by the MainLayout component:

Figure 2.14 – Screen layout

Figure 2.14 – Screen layout

Tip

The Blazor WebAssembly App project template uses Bootstrap 4 to style its pages. If you are unfamiliar with Bootstrap 4, you should refer to https://getbootstrap.com to familiarize yourself with its syntax.

The NavMenu component

The NavMenu component defines the navigation menu for the Demo project. It uses multiple NavLink components to define the various menu options. This is the section of the NavMenu component that references the NavLink components used for the project's navigation:

<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
    <ul class="nav flex-column">
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="" 
                     Match="NavLinkMatch.All">
                <span class="oi oi-home" 
                      aria-hidden="true"></span> Home
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="counter">
                <span class="oi oi-plus" 
                      aria-hidden="true"></span> Counter
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" 
                      aria-hidden="true"></span> Fetch data
            </NavLink>
        </li>
    </ul>
</div>

The NavLink component is defined in the Microsoft.AspNetCore.Components.Routing namespace. It behaves like an a element, except it has added functionality that highlights the current URL. This is the HTML that is rendered by NavLink for the Counter component when the Counter component is selected:

<a href="counter" class="nav-link active">
    <span class="oi oi-plus" aria-hidden="true"></span> 
    Counter
</a>

The style used for the nav-link class is from Bootstrap. The style used for the active class is defined in the wwwroot\css\app.css file:

.sidebar .nav-item a.active {
    background-color: rgba(255,255,255,0.25);
    color: white;
}

The SurveyPrompt component

The SurveyPrompt component creates a link to a brief survey on Blazor.

Examining the routable Razor components

The routable Razor components are in the Pages folder. There are three routable Razor components in the Demo project:

  • The Index component
  • The Counter component
  • The FetchData component

The Index component

The Home page of the Demo project uses the Index component that is defined in the Pages\Index.razor file:

Pages\Index.razor

@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />

The preceding code includes an @page directive that references the root of the web app and some markup. The markup includes a SurveyPrompt component.

The Counter component

The Counter component is more complex than the Index component. Similar to the Index component, it contains an @page directive that is used for routing and some markup. However, it also contains a C# code block:

Pages\Counter.razor

@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">
    Click me
</button>
<a href="counter" class="nav-link active">
    <span class="oi oi-plus" aria-hidden="true"></span> 
    Counter
</a>
@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}

In the preceding code block, a private currentCount variable is used to hold the number of clicks. Each time the Counter button is clicked, the Counter component's registered @onclick handler is called. In this case, it is the IncrementCount method.

The IncrementCount method increments the value of the currentCount variable and the Counter component regenerates its render tree. Blazor compares the new render tree against the previous one and applies any modifications to the browser's DOM. This results in the displayed count being updated.

The FetchData component

The FetchData component is by far the most complex component in the Demo project.

These are the directives in the Pages\FetchData.razor file:

@page "/fetchdata"
@inject HttpClient Http

The @page directive is used for routing and the @inject directive is used for dependency injection. In this component, HttpClient that is defined in the Program.cs file is being injected into the view. For more information on dependency injection, refer to Chapter 6, Building a Shopping Cart Using Application State.

The following markup demonstrates the use of a very important pattern that you will often use when developing a Blazor WebAssembly application. Because the application runs on the browser, all data access must be asynchronous. That means that when the page first loads, the data will be null. For that reason, you need to test for the null case before attempting to process the data.

This is the markup in the Pages\FetchData.razor file:

<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                   <td>@forecast.Date.ToShortDateString()
                      </td>
                   <td>@forecast.TemperatureC</td>
                   <td>@forecast.TemperatureF</td>
                   <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

The preceding markup includes an if statement and a foreach loop. While the value of forecasts is null, a Loading message is displayed. If you do not handle the case when the value of forecasts is null, the framework will throw an exception. Once the value of forecasts is no longer null, all of the items in the array are presented in a table.

Important note

The value of forecasts will be null the first time that the page is rendered.

As previously mentioned, Blazor components have a well-defined life cycle. The OnInitializedAsync method is invoked when the component is rendered. After the OnInitializedAsync method completes, the component is re-rendered.

This is the code block in the Pages\FetchData.razor file:

@code {
    private WeatherForecast[] forecasts;
    protected override async Task OnInitializedAsync()
    {
        forecasts = await 
            Http.GetFromJsonAsync<WeatherForecast[]>
            ("sample-data/weather.json");    
    }
    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }
        public int TemperatureF => 
            32 + (int)(TemperatureC / 0.5556);
    }
}

First, the preceding code block declares a parameter to contain an array of the type WeatherForecast. Next, it uses the OnInitializedAsync asynchronous method to populate the array. In order to populate the array, the GetFromJsonAsync method of the HttpClient service is used. For more information on HttpClient, refer to Chapter 8, Building a Task Manager Using the ASP.NET Web API.

Using a component

Razor components are used by including them in the markup of another component. We will add a Counter component to the Home page. We do this as follows:

  1. Return to Visual Studio.
  2. Open the Pages\Index.razor file.
  3. Delete all of the markup. Be sure you do not remove the @page directive at the top of the file.
  4. Add the following markup below the @page directive:
    <Counter />
  5. From the Build menu, select the Rebuild Solution option.
  6. Return to the browser and navigate to the Home page. If the Demo project is not still running, from the Debug menu, select the Start Without Debugging (Ctrl+F5) option to run it.
  7. Use Ctrl + R to refresh the browser.

    Tip

    Whenever you update your C# code, you need to refresh the browser for the browser to load the updated DLL.

  8. Click the Click me button to test the Counter component.

Adding a parameter to a component

Most components require parameters. To add a parameter to a component, use the Parameter attribute. We will add a parameter to specify the increment used by the IncrementCount method. We do this as follows:

  1. Return to Visual Studio.
  2. Open the Pages\Counter.razor file.
  3. Add the following code to the top of the code block to define the new parameter:
    [Parameter] public int? Increment { get; set; }
    private int increment = 1;
  4. Update the IncrementCount method to the following:
    private void IncrementCount()
    {
        currentCount += increment;
    }
  5. Add the following OnParametersSet method to set the value of increment to the value of the Increment parameter:
    protected override void OnParametersSet()
    {
        if (Increment.HasValue)
            increment = Increment.Value;
    }
  6. Add the highlighted text to the markup of the Click me button to display the current value of the increment variable:
    <button class="btn btn-primary" 
            @onclick="IncrementCount">
        Click me (@increment)
    </button>

Using a parameter with an attribute

We will add another instance of the Counter component to the Home page that uses the new parameter. We do this as follows:

  1. Open the Pages\Index.razor file.
  2. Add the following markup to the bottom of the Index.razor file:
    <Counter Increment="5"/>

    As you add the markup, IntelliSense is provided for the new Increment parameter:

    Figure 2.15 – IntelliSense

    Figure 2.15 – IntelliSense

  3. From the Build menu, select the Build Solution option.
  4. Return to the browser.
  5. Use Ctrl + R to refresh the browser.
  6. Navigate to the Home page.

    The Home page now contains two instances of the Counter component. If you click the first Click me button, the first counter will be incremented by 1; if you click the second Click me button, the second counter will be incremented by 5:

    Figure 2.16 – The Home page

    Figure 2.16 – The Home page

  7. Click each of the Click me buttons to verify they both work as intended.

Adding a route parameter

Components can have multiple @page directives. We will add an @page directive to the Counter component that uses a parameter. We do this as follows:

  1. Return to Visual Studio.
  2. Open the Pages/Counter.razor file.
  3. Add the following @page directive to the top of the file:
    @page "/counter/{increment:int}"

    The Counter component now includes two @page directives.

  4. From the Build menu, select the Build Solution option.
  5. Return to the browser.
  6. Navigate to the Counter page.
  7. Update the URL to the following:
    /counter/4

    Important note

    Since the page is automatically reloaded when you change the URL, you do not need to refresh the browser in order to reload the page.

  8. Click the Click me button.

    The counter should now increment by 4.

  9. Update the URL to an invalid route:
    /counter/a

    Since this is not a valid route, you will be directed to the NotFound content defined in the App component:

Figure 2.17 – Page not found

Figure 2.17 – Page not found

Tip

If you need to navigate to a URL in code, you should use NavigationManager. NavigationManager provides a NavigateTo method that is used to navigate the user to the specified URI without forcing a page load.

Using partial classes to separate markup from code

Many developers prefer to separate their markup from their C# fields, properties, and methods. Since Razor components are regular C# classes, they support partial classes. The partial keyword is used to create a partial class. We will use a partial class to move the code block from the RAZOR file to a CS file. We do this as follows:

  1. Return to Visual Studio.
  2. Right-click the Pages folder and select Add, Class from the menu.
  3. Name the new class Counter.razor.cs.
  4. Update the Counter class to be a partial class by using the partial keyword:
    public partial class Counter{}
  5. Open the Pages/Counter.razor file.
  6. Copy all of the code in the code block to the partial Counter class in the Counter.razor.cs file.
  7. Delete the code block from the Counter.razor file.
  8. Add the following using statement to the Counter.razor.cs file:
    using Microsoft.AspNetCore.Components;
  9. From the Build menu, select the Build Solution option.
  10. Return to the browser.
  11. Use Ctrl + R to refresh the browser.
  12. Navigate to the Counter page.
  13. Click the Click me button to verify that it still works.
  14. Close the browser.

Using partial classes gives you the flexibility to move the code in the code block to a separate file, allowing you to use the code-behind technique.

We have created a Demo project by using the Blazor WebAssembly App project template provided by Microsoft. We added a parameter to the Counter component and moved the code in the code block of the Counter component to a separate file.

Creating a custom Blazor WebAssembly project template

As you have seen, the Demo Blazor WebAssembly project created by the Blazor WebAssembly App project template includes quite a few files. In later chapters, we will want to start with an empty Blazor project. So, we will create our own project template that creates an empty Blazor WebAssembly project.

Creating an empty Blazor project

We need to create an empty Blazor WebAssembly project to base our new project template on. We do this as follows:

  1. Return to Visual Studio.
  2. Delete the wwwroot\sample-data folder.
  3. Delete all of the components in the Pages folder, except for the Index component.
  4. Open the Index.razor file.
  5. Delete all of the markup from the Index component. Make sure that you do not delete the @page directive at the top of the page.
  6. Delete the Shared\SurveyPrompt.razor file.
  7. Open the Shared\MainLayout.razor file.
  8. Remove the About link from the top row of the layout by removing the following markup:
    <a href="http://blazor.net" target="_blank"
       class="ml-md-auto">
            About
    </a>
  9. Open the Shared\NavMenu.razor file.
  10. Remove the li elements for the Counter and Fetch data pages.
  11. From the Build menu, select the Build Solution option.
  12. From the Debug menu, select the Start Without Debugging (Ctrl+F5) option to run the Demo project.

    The Demo project is now empty. It only contains a blank Home page.

Creating a project template

The Export Template Wizard is used to create custom project templates. We will use the empty project that we just created as the basis for a custom project template. We do this as follows:

  1. Return to Visual Studio.
  2. From the Project menu, select the Export Template option to open the Export Template Wizard window.
  3. Select Project template on the Choose Template Type dialog and click the Next button:
    Figure 2.18 – The Choose Template Type dialog

    Figure 2.18 – The Choose Template Type dialog

  4. Complete the Select Template Options dialog as shown in the following screenshot and click the Finish button:
Figure 2.19 – The Select Template Options dialog

Figure 2.19 – The Select Template Options dialog

After you click the Finish button, your new project template will be saved to the folder indicated in the Output location field on the Select Template Options dialog and the folder will automatically open. The files that comprise your new project template are compressed into a file called EmptyBlazorProject.zip.

Updating a custom project template

We need to make a few updates to our custom project template before it is ready to use. First, we will declare a template parameter for the project's name, and then we will update the metadata. We do this as follows:

  1. Extract all of the files from the EmptyBlazorProject.zip file.

    The EmptyBlazorProject.zip file contains all of the files from the empty Demo project as well as a MyTemplate.vstemplate file that contains all of the metadata for the project template.

  2. Open the Shared/NavMenu.razor file and replace the word Demo with $projectname$:
    <a class="navbar-brand" href="">$projectname$</a>

    The $projectname$ parameter will be replaced by the name of the project that is provided by the user when the project is created.

    Open the _Imports.razor file and replace the word Demo with $projectname$:

    @using $projectname$
    @using $projectname$.Shared
  3. Open the MyTemplate.vstemplate file.
  4. Update the value of the Name element to Empty Blazor WebAssembly App:
    <Name>Empty Blazor WebAssembly App</Name>
  5. Add the following elements after the Description element:
        <LanguageTag>C#</LanguageTag>
        <ProjectTypeTag>Web</ProjectTypeTag>
  6. Replace the Icon element with the following Icon Package element:
    <Icon Package="{AAB75614-2F8F-4DA6-B0A6-763C6DBB2969}" ID="13"/>
  7. Change the ReplaceParameters attribute to true for NavMenu.razor ProjectItem:
    <ProjectItem ReplaceParameters="true" 
                 TargetFileName="NavMenu.razor">
        NavMenu.razor
    </ProjectItem>
  8. Change the ReplaceParameters attribute to true for _Imports.razor ProjectItem:
    <ProjectItem ReplaceParameters="true" 
                 TargetFileName="_Imports.razor">
        _Imports.razor
    </ProjectItem>
  9. Save all of the updated files.
  10. Update the EmtpyBlazorProject.zip file with the updated files.
  11. Copy EmtpyBlazorProject.zip from the Visual Studio 2019\MyExportedTemplates folder to the Visual Studio 2019\Templates\ProjectTemplates folder.

Using a custom project template

We can use a custom project template the same way that we use any of the built-in project templates. We do this as follows:

  1. From the File menu, select the New, Project option.
  2. Enter Blazor in the Search for templates textbox to locate your new template:
    Figure 2.20 – Empty Blazor WebAssembly App template

    Figure 2.20 – Empty Blazor WebAssembly App template

  3. Select the Empty Blazor WebAssembly App template and click the Next button.
  4. Update the project name to Sample and click the Create button.
  5. From the Build menu, select the Build Solution option.
  6. From the Debug menu, select Start Without Debugging (Ctrl+F5).

We have created a new Sample project by using our custom project template. The only page in the Sample project is the Home page.

We created an empty project by deleting some of the components and code from the Demo project that we created in the previous section. Then, we used the Export Template Wizard to create a custom project template based on the empty project. After we updated some of the files in the custom project template, we copied them into the ProjectTemplates folder. Finally, we used the custom project template to create the Sample project.

Summary

You should now be able to create a Blazor WebAssembly application.

In this chapter, we introduced Razor components, routing, and Razor syntax.

After that, we used the Blazor WebAssembly App project template provided by Microsoft to create the Demo Blazor WebAssembly project. We added a parameter to the Counter component and examined how routing works.

In the last part of the chapter, we created an empty Blazor WebAssembly project on which to base our own custom project template. We created a custom project template using the Export Template Wizard. After we finished configuring our custom project template, we used it to create an empty Blazor WebAssembly project.

We will use the Empty Blazor WebAssembly App project template to create the project in the next chapter of this book.

Questions

The following questions are provided for your consideration:

  1. Can Razor components include JavaScript?
  2. What types of loops are supported by Razor syntax?
  3. Can the Blazor App project template be used to create both Blazor WebAssembly applications and Blazor Server applications?
  4. What are the advantages of using a custom project template?
  5. How would you create your own custom item template to automatically create a code-behind page for each new component?

Further reading

The following resources provide more information concerning the topics in this chapter:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore complete, easy-to-follow web projects using Blazor
  • Build projects such as a weather app, expense tracker, and Kanban board with real-world applications
  • Understand and work with Blazor WebAssembly effectively without spending too much time focusing on the theory

Description

Blazor WebAssembly makes it possible to run C# code on the browser instead of having to use JavaScript, and does not rely on plugins or add-ons. The only technical requirement for using Blazor WebAssembly is a browser that supports WebAssembly, which, as of today, all modern browsers do. Blazor WebAssembly by Example is a project-based guide for learning how to build single-page web applications using the Blazor WebAssembly framework. This book emphasizes the practical over the theoretical by providing detailed step-by-step instructions for each project. You'll start by building simple standalone web applications and progress to developing more advanced hosted web applications with SQL Server backends. Each project covers a different aspect of the Blazor WebAssembly ecosystem, such as Razor components, JavaScript interop, event handling, application state, and dependency injection. The book is designed in such a way that you can complete the projects in any order. By the end of this book, you will have experience building a wide variety of single-page web applications with .NET, Blazor WebAssembly, and C#.

Who is this book for?

This book is for .NET web developers who are tired of constantly learning new JavaScript frameworks and wish to write web applications using Blazor WebAssembly, leveraging the power of .NET and C#. The book assumes beginner-level knowledge of the C# language, .NET framework, Microsoft Visual Studio, and web development concepts.

What you will learn

  • Discover the power of the C# language for both server-side and client-side web development
  • Use the Blazor WebAssembly App project template to build your first Blazor WebAssembly application
  • Use templated components and the Razor class library to build and share a modal dialog box
  • Understand how to use JavaScript with Blazor WebAssembly
  • Build a progressive web app (PWA) to enable native app-like performance and speed
  • Understand dependency injection (DI) in .NET to build a shopping cart app
  • Get to grips with .NET Web APIs by building a task manager app

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 09, 2021
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781800563933
Vendor :
Microsoft
Languages :
Tools :

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
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Jul 09, 2021
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781800563933
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 130.97
C# 10 and .NET 6 – Modern Cross-Platform Development
€59.99
Blazor WebAssembly by Example
€32.99
Web Development with Blazor
€37.99
Total 130.97 Stars icon

Table of Contents

10 Chapters
Chapter 1: Introduction to Blazor WebAssembly Chevron down icon Chevron up icon
Chapter 2: Building Your First Blazor WebAssembly Application Chevron down icon Chevron up icon
Chapter 3: Building a Modal Dialog Using Templated Components Chevron down icon Chevron up icon
Chapter 4: Building a Local Storage Service Using JavaScript Interoperability (JS Interop) Chevron down icon Chevron up icon
Chapter 5: Building a Weather App as a Progressive Web App (PWA) Chevron down icon Chevron up icon
Chapter 6: Building a Shopping Cart Using Application State Chevron down icon Chevron up icon
Chapter 7: Building a Kanban Board Using Events Chevron down icon Chevron up icon
Chapter 8: Building a Task Manager Using ASP.NET Web API Chevron down icon Chevron up icon
Chapter 9: Building an Expense Tracker Using the EditForm Component Chevron down icon Chevron up icon
Other Books You May Enjoy 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.5
(12 Ratings)
5 star 66.7%
4 star 16.7%
3 star 16.7%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Jul 14, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Packt never fails to impress with their content. Blazor WASM is an awesome new tool and this teaches you everything you need to know to make a well designed application. Like all Packt books, it is easy to pick up in different chapters depending on what you want to learn. I was specifically looking more into how to make a PWA with Blazor and this was a fantastic guide!
Amazon Verified review Amazon
Paul Schroeder Jul 26, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I appreciate the author’s “no fluff” approach to covering all the basics Blazor developers need to know. As someone who has developed a few Blazor applications already, this meant that I was able to finish the content in just a few sessions. Being somewhat experienced, I certainly did pick up some new information, but I think beginner-to-intermediate developers will get the most out of this book.Personally, I thought the use of project templates was very appropriate and I wish more Visual Studio developers made use of this gem of an IDE feature. The sections on RenderFragment, EventCallback, CSS isolation, attribute splatting, and JS Interop were explained nicely. Content on Progressive Web Apps contained details, like the service worker life cycle, that were good to learn more about.I was impressed at the author’s ability to present straightforward examples, each of which demonstrated a Blazor capability with minimal code. Sticking close to just what is needed made it easy to understand what was happening.Overall, I liked this book, which is clearly designed to be a quick overview of each topic. After covering the basics, the author provides “further reading” sections at the conclusion of each chapter to make it easy to go deeper, if desired. There are also sample questions along the way that help you gauge your knowledge or think about what could be next if you want to experiment with extending the project samples.
Amazon Verified review Amazon
Adam Smith Apr 10, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has a very pleasant way of teaching. A kind of step-by-step way. I give it a full 5 stars.
Amazon Verified review Amazon
Daniel Correa Aug 08, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Blazor WebAssembly is the Microsoft's single-page application (SPA) framework for building web applications on .NET Framework. It is another option that front-end developers should have in mind. One of the main difference with their main competitors (Vue, React, Angular) is that it enables developers to run C# code on the client. It means, you can develop an entire SPA application without using JavaScript.Toi (the author of this book) teaches us how to use Blazor WebAssembly in a practical way. She provides a set of projects and examples which are very useful and which teaches us the fundamental elements of Blazor WebAssembly. For example, (i) you will implement a simple modal dialog application, which focuses on razor elements, components, and RenderFragments. (ii) You will implement a simple data storage application, which explains how to use JS Interop to execute some JavaScript commands from a Blazor WebAssembly application (there are some cases in which using JavaScript makes sense). (iii) You will implement a Weather App which uses service workers, APIs, and implementation of PWA applications. And (iv) even, it takes you to develop a complete front-end and back-end application (task manager) with the use of an ASP.NET Web API. Other topics and projects include: application state, events, edit forms, and dependency injection.All those projects (and many others) present proper explanations, with excellent examples. The code of the projects is easy to follow, simple, and properly detailed. Therefore, you can use some of those projects as a base to develop your own applications.This is a totally recommended book if you want to learn Blazor WebAssembly in a practical way, with very useful examples, and short explanations. Congratulations to the author.
Amazon Verified review Amazon
Justin Horner Jul 15, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I love reading through example-focused books, and Blazor by Example is no exception! As the title states, this is a project-based guide to building web apps with .NET, Blazor WebAssembly, and C#.On your journey through learning Blazor by Example, you'll create several applications that scale up in complexity by chapter. Everything from creating your first Blazor application and making a weather app PWA to handling application state in a shopping cart experience gets covered throughout the projects in the book.I highly recommend this book to anyone interested in Blazor. It's a great learning resource and reference for Blazor WebAssembly projects.Here are a few of my chapter/topic highlights:- JS Interop- Building a Progressive Web App (PWA)- Using Application State- Building a Kanban Board using Events- Building a Task Manager using ASP.NET Web API
Amazon Verified review Amazon
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.