Welcome to part one of a five-part educational series on Blazor Server in .NET 6.
In this series, we will create a Character Builder that will help track your Character as you and your friends explore unknown worlds. The main topics in this series will include…
- Step-by-step instructions for creating a new Blazor Server application
- An overview of what files are included in the Blazor Server Template provided by Microsoft
- Creating reusable Blazor components using code-behind files and component scoped
- How to use the
ProtectedBrowserStorageto safely store information in an encrypted
- How to use 3rd party components for faster development
- Using Popup Modals for your forms with the
- Advanced topics such as creating an
EventBuswhere components are able to publish and subscribe to events
- One and two-way data-binding
- Calling APIs using a wrapper around the .NET
By the end of this series, you will be able to create a SPA application using Blazor. You will be able to quickly access and store data from an API, display that on the screen in reusable components, and have your components react to events dynamically to allow for a great user experience!
In part one, we will learn how to create a new Blazor server application and understand what is going on under the hood. We will discuss the standard template files you’ll see when creating a new application and cover the functionality and syntax that will be inside the provided Blazor components.
We’ll then go step by step to create a Blazor page, navigate to our new page, create a Character Component to display our character, and display a list of characters on our Character Page. We will also be looking at the component lifecycle with examples of how they function when attempting to display our characters.
Let’s dive in!
Quick Introduction To Blazor
Blazor is a framework for building interactive client-side web UI with .NET. Blazor was started in 2018 by Microsoft as a SPA framework that could be written entirely in C# using Razor pages. This allows full-stack web development with stability, consistency, and productivity native to .NET.
Bonus: If you are already familiar with React, Vue, or Angular, then much of the way the Blazor UI is structured should look very familiar.
Creating a New Blazor Application
There are two ways to create a new Blazor application: through the CLI or using Visual Studio. I’ll explain both below.
Use Visual Studio
1. Install Visual Studio
- Make sure that when you install the ASP.NET workload, it includes .NET 6 runtime and SDKs.
2. Launch Visual Studio, and click on Create a new project.
3. Search for the Blazor Server App template.
4. Choose a name for your project, and decide if you want the solution and project in the same directory.
For the sake of this example, select the .NET 6 Lts with no authentication and configure for HTTPS without Docker.
5. Then Create!
Congratulations you have a running Blazor Server app!
Use the CLI
1. [Install](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) the .NET 6 runtime and SDK. Run the following command.
dotnet new blazorserver -o [NameOfApplication]
2. Open in IDE and you are ready to go!
I know that most people use a TodoList app to demo functionality…. but that seems a little boring.
Instead, let’s build a Character Creator app for your favorite role-playing game! I called my app CharacterBuilder so you will see that in my file structure and throughout the rest of the demo.
Template File Structure
The template file structure should look like a bit of a mix between a .NET MVC app and a React.js app. If you are coming from a .NET background but haven’t used .NET 6 yet, then one thing you will notice is that there is no
Startup.cs file. This has been combined into the
Program.cs file for a single file experience.
You will see a Data folder where Blazor put a mock data service. You can put your API services in here but it’s not required. The Pages folder contains the default pages that Blazor comes with. The important files here are the
_Layout.cshtml, and they don’t really need to be changed unless you are doing something pretty specific. The Shared folder contains some navigation components for changes routing between pages in the Blazor SPA world.
App.Razor provides a default layout and the
_imports.razor is where Blazor looks for Global using statements. There is not a whole lot to the template, but it really helps you get an app off the ground.
The following are some of Blazor Server’s default pages. I included a brief explanation of each as well.
App.razor contains the route view with a default layout. Similar to React, all our components sit atop the
MainLayout.razor in the Shared Folder
Without previous tampering,
App.razor is set to
MainLayout, which is this component. If you wish to use a different default layout, you can choose to create a custom layout, and set it in the
This file contains the
NavMenu component in a sidebar. Any component with the
@page in the Blazor Template has a Nav Item here to navigate between pages
NavMenu.razor contains HTML and an
@code block that contains C# code for MVVM.
The top button contains an
@onClick method that allows you to select a C# method in either your code block or code behind the file to run when the button is clicked.
NavLink component has an href tag that allows you to navigate to other pages. Those pages will display in the
@body of the
This is the landing page for our new Blazor application.
Notice that at the top of the file, the page route is
/. Underneath that is the page title, which sets the title in the tab of the webpage.
The is a component defined in
Shared/SurveyPrompt. The Title is a property similar to React that is passed to the
SurveyPrompt component. One of the nice things about Blazor is the ability to use Visual Studio IntelliSense to determine the available properties of a component.
As with the Index page, the counter page has a route found at the top of the file using the
Using one-way data binding to display the current count can be done using the
@ symbol to access a property in the code block or inherited class, which we will talk about later.
IncremementCount method is called when the button is clicked using the
New in this component is that we are injecting the
WeatherForecastService directly into our component using
We will also use our first Component lifecycle event by overriding the
OnInitializedAsync method. This method is called the first time a component is rendered. This method gets forecast information from a mock data service and sets the property of forecasts, which can be displayed on our table.
Additional Default Settings
Below, I’ve listed additional default settings.
launchSettings.jsonfile can be found in the Properties folder.
- Bootstrap 5 can be found in the
wwwroot/cssfolder and will work with IntelliSense inside our razor files.
_Imports.razorfile is where we store any using statements that we would like to add to all our razor components globally. This saves a lot of room at the top of our components and prevents the cluttering of files by using statements.
- I usually edit the project file and remove the enable so that I don’t get warnings for potentially null properties.
Create a CharacterModel
Now let’s jump into creating our
CharacterModel is going to be pretty simple, but can always be added to later. Displaying your character information looks better on screen with more information, but this is a great starting point.
Create a CharacterInfo Component
For starters, I think it’s helpful to add a Components folder to hold all your non-page components in one place. We will take the following steps to create a
1. Create a new razor component called
CharacterInfo. Some people choose to add “Component” to the end of their non-page components – this is a personal preference.
2. Remove the
@code block and
h3 tag for now.
3. In the same folder, create a new class called
CharacterInfo.razor.cs. This will be our code behind the file for this component. It is important to name this file the same as your component file with the .cs on the end as this will allow Visual Studio to organize your files correctly.
4. You will see that this gives us an error that another partial class of the same name exists. You have two options, make this a partial class or change the class name. You want the file to be named as it is, so the code behind functionality works correctly.
I always choose to rename the class with “Base” at the end giving me
Microsoft.AspNetCore.Components, your Base component should inherit from
5. Add a property to the
CharacterInfoBase for a CharacterModel called…
6. Add a data annotation
[Parameter] to the Character property. This allows you to pass a
CharacterModel object to the component as a parameter.
7. Back in the
Character.razor file, add a
@inherits CharacterInfoBase if you chose to use the base class option instead of the partial class option. Create a simple card component to display your character information.
Now it’s time to add styling. Blazor uses both scoped style sheets and global styles, but scoped styles take precedence over global styles. In order to create a scoped style sheet, we will use Scss to show how to compile the file correctly.
Blazor looks for a .css code behind the file automatically when using scoped styles. This looks like
1. First, let’s create a
CharacterInfo.razor.scss file and compile that into a
2. Once you have created your file (the same way you created the code behind .cs file), add this CSS to give our container a border.
3. Next, we will compile our SCSS file. Under tools -> Manage Extensions, install the Web Compiler 2022+ by Jason Moore. Restart Visual Studio for these changes to take effect.
4. Right-click on the .SCSS file -> Web Compiler -> Compile file. This will create a compilerconfig.json file.
The contents of your
compilerconfig.json file should look like this. While it doesn’t show it here, the compiler outputs a .min.css file as well.
That completes our work on the
CharacterInfo component for now! But don’t worry; we will continue to update it later down the road.
It’s time to create our Characters page, which will display our
CharacterInfo components and allow us to add new characters in the future. We will also cover getting some mock characters from a character service, adding that service to DI, injecting the service into our page component, and looping through our
1. In the pages folder, create a Razor component. I chose to call mine
CharactersPage for the sake of simplicity. I saw that a Blazor dev used this as a naming convention, and I’ve chosen to do the same.
2. Remove the code so the only code in your file is the routing information
@page “/Characters”. Note: This requires using the / and will not work without it.
3. Add a code behind the file for the
CharactersPage. Refer to the
CharacterInfo component if you need to.
4. Create a folder in the root directory of our app called Services. Then create a new class called
CharacterService. I created an Async method that returns a list of
CharacterModels to show how to return information async. Feel free to add a delay for a more realistic feel of hitting a server for information.
5. Add an interface for the
CharacterService you just created.
6. In the Program.cs file, add the
ICharacterService to the DI container using
builder.Services. This should be old news to anyone familiar with .NET.
7. To inject our
ICharacterService into the
CharactersPage component, we add the [Inject] data annotation to the top of the property on our page. After that, we can set our
CharacterModels to the result of our
CharacterService method in the
Remember that the page will display while this call is being made. To prevent a null exception on our list of
CharacterModels, we should make sure the
CharacterModels property is not null by newing it up using either the constructor or in the
SetProperties override method.
8. Now that we have our characters, we can display them on the screen. If you are familiar with another component-based UI, then this should look familiar to you.
Now, we loop through our
CharacterModels in our base class and pass the character as a property to the
9. The final step to get this all to work is to add our page to the navigation. At this point, you can type the page route into the URL and it will work, although no one wants to do that over and over again.
Instead, add a new NavLink for the
CharactersPage in the
NavMenu.razor file. The href should correspond to the
@page tag in the
10. Run our application and click on the “Characters” link. It should show you the mock characters you created! Congratulations, you’ve done it!
In Part 1 of the Keyhole Blazor Server in .NET 6 series, we learned how to create a new Blazor server application with both the CLI and Visual Studio methods. We covered the default template files that are provided when creating a new application and talked through some of the functionality and syntax inside the default components.
This gave us a brief primer for creating our own Character Builder application, so we created a Blazor page, navigated to our new page, and created a component to display data on a Character Page. We were able to see how component lifestyles function when attempting to display our characters as well.
Hopefully, Part 1 provided a helpful outline for navigating the
CharactersPage component in further installments of the .NET 6 series. See you in Part 2, where we build on this application to utilize Blazor Protected Browser Storage.