Masa blazor introduction is enough


1. What is blazor? What are the advantages?

ASP. Net core blazor introduction

Blazor is a framework for generating interactive client Web UI using blazor:

  1. Use c# instead of JavaScript to create an informative interactive UI.
  2. Shared use Net.
  3. Render the UI as HTML and CSS to support many browsers, including mobile browsers.
  4. Integration with new hosting platforms such as docker.

Blazor benefits:

  1. Use C # instead of JavaScript to write code.
  2. Make use of existing Net library ecosystem.
  3. Share application logic between server and client.
  4. Benefit from Net.
  5. Keep working efficiently with visual studio on windows, Linux, and MacOS.
  6. It is generated based on a set of stable, functional and easy-to-use general-purpose languages, frameworks and tools.

2. Why Masa blazor? What can it be used for?

Masa blazer is a UI component library based on Blazer component and material design.
Dotnet developers do not need to know JavaScript to develop an enterprise level middle and background system.
Masa blazor benefits:

  • Rich components: including the basic components of vuetify 1:1 restore, as well as many practical preset components and Net deep integration functions, including URL, bread crumbs, navigation, advanced search, I18N, etc.
  • UI design language: modern design style, excellent UI multi terminal experience design.
  • Easy to get started: rich and detailed documentation, free video tutorials (in production).
  • Active community encourages: users to participate in real-time interaction, make contributions, join us, and build the most open source community.
  • Long term support: full time team maintenance and provide enterprise level support.
  • Professional example: Masa Blazer Pro provides preset layouts for a variety of common scenes.

Example of blazor Pro preset layout:

See if some students here are interested in it! So how is such a layout page built? Can we build such a layout ourselves! hey! Don’t worry, let’s look down.

3. Create the first blazor program using the Masa blazor template

1. First install Masa Template template

(1) Check the machine Net SDK version, please make sure it is installed NET6. 0

(2) Install Masa Template template, including all project templates of masa series
dotnet new –install Masa.Template

2. Create project

dotnet new masab -o MasaBlazorApp
The default is server mode. You can create a webassembly mode project through the parameter — mode webassembly

3. Configure Masa Blazer (because I use the template here, the following configurations have been configured for us in the template. After installing the template, you can directly dotnet run; for students who do not install the template, you can configure it according to the following steps)

(1) Install nuget package

dotnet add package Masa.Blazor

(2) Import resource files (blazor server in my case)

On pages/_ Layout. Introducing resource files into cshtml

(3) Inject related services

In program Add Masa to CS Blazor related services


(4) Modification_ Imports. Razor file, add the following:

@using Masa.Blazor

(5) Run project

Here, a simple Masa blazor project is completed. Of course, this is only the most basic. Next, we will use Masa blazor project components step by step to enrich our project.

3. Configure the project using Masa blazor components


(1) Introduction to blazor application structure

First, let’s take a look at the blazor project structure and analyze the functions of several main documents. (the concept definition is boring. Students who want to experience it directly can skip this part and practice it directly, but it is not recommended. There is a saying that “sharpening a knife does not make a mistake for cutting firewood”


The entry point of blazor server application is in program CS file, the same as the console application. When the application executes, it creates and runs a web host instance using web application specific defaults. The web host manages the lifecycle of the blazor server application and sets up host level services.

stayBlazor server applicationIn, the displayed program The. CS file is used to set the endpoint for the real-time connection that blazor uses between the client browser and the server.
stayBlazorwebassembly applicationProgram The CS file defines the root component of the application and its rendering location:

In program In the CS file, we first focus on the following points:

1. In dependency injection, because we use razor to realize the mixed coding of c# and HTML, and we use razor of serverside, the injection code is as follows:

The middleware is as follows:


In the blazor server application, the host page of the root component is_ Host. Defined in cshtml file. This file defines a razor page, not a component. Razor pages uses razor syntax to define server addressable pages.

In program CS file will automatically go to our configuration_ Host. Find the root component in the cshtml file
This is the default use of the app component as the root component (this is one of the necessary conditions for starting the blazor application)

So what is the render mode feature used for?
Let’s take a look at the official document explanation:

The root component of the blazor application, which usually contains the router component, is used to handle the routes in blazor

What are the functions of these parameters in the router component, such as appassembly, found and notfound?

By reading the official documents, we can find that:

The router component will find routable components in the specified appassemblies and additionalassemblies (optional). When the browser navigates, if a route matches the address, the router will intercept the navigation and present the content of its found parameter and the extracted routedata. Otherwise, the router will present its notfound parameter.

The routeview component is responsible for rendering the matching components specified by routedata and their layout, if any. If there is no layout for the matching component, use the selectable defaultLayout.

The layoutview component renders its child content within the specified layout

That is to say, we are finishing the configuration After routing the razor page, the router component will match the route with the address when the browser navigates. If it can match, the router will intercept the navigation and present the matching component and layout specified by its found parameter (we specify the mainlayout layout page here). On the contrary, it will present the notfound parameter.


Before_ Host. In the cshtml file, we specify that it is enabled by default_ Layout. Cshtml layout page

_ Layout. Cshtml is the host page of blazor application (equivalent to a root page layout file), which contains the application’s initialization HTML and its components. It makes it easier for us to maintain the appearance of all page layouts.


In blazor, the layout component is used to process the page layout. The layout component is inherited from layoutcomponentbase, which defines a single body attribute of type renderfragment, which can be used to render the content of the page.

Global import configuration. After using using import here, it is equivalent to importing in all razor files.

Well, there’s a lot of nonsense. Here, the main structural concepts of blazor application have almost been introduced. Interested students can move to the official website for readingWeb oriented forms ASP Net web forms developer blazor
Next, let’s start with the code

(2) Use app bars and navigation drawers to configure the navigation bar and menu bar

In the above page display, we can see three menu pages, which are configured with corresponding routes respectively
The corresponding page of home is index Razor, route is “/”

The corresponding page of counter is counter Razor, route is “/ counter”

The fetch data page corresponds to fetch data Razor page route, the route is “/ fetchdata”
In shared / mainlayout We can see the configuration in the razor page.

Next, let’s move directlyMasa blazor official website addressFind examples of components we need:

Let’s copy the sample code directly to shared / mainlayout The mappbar component in the razor page is sufficient

Dotnet run to see the effect

Next, we find the navigation drawers component in the Masa razor component library and copy the razor page code and c# code toIn the component

We made a slight modification to the code

Dotnet run to see the effect

Next, let’s implement the dynamic menu bar scaling function and find the mini mode of the navigation drawers component

Next, let’s transform our code

Dotnet run to see the effect

Does it feel super simple! Of course, this is just an introductory writing method. Interested students can try it and draw inferences from one instance to unlock the usage and writing methods of more components

(3) Use datatable, dialog and other components to realize a basic data interaction page

First, we initialize fetch Razor, only one is the simplestassembly

Datatable component needs to bind at least one header and data source
So next, let’s define headers and items (just call the API to get the data actually. The default dead data here is for reference only)
Let’s build a fetch Partial class of razor page, defining partial code

Dotnet run to see the effect

In the above code screenshot, we will find that we use the oninitializedasync () method, so what is this method used for? Speaking of this problem, we need to understand the life cycle of razor components firstASP. Net core razor component lifecycle

Let’s start with a component lifecycle diagram

Setparametersasync – when setting parameters

This method is executed whenever the parent renders.
The parameters passed in to the component are contained inParameterViewYes. This is a good time to make asynchronous calls to the server (for example) based on the state of the incoming component.
Call in overridebase.SetParametersAsync(Parameters)When, the[Parameter]Attribute assignment.
It is also the correct place to specify the default parameter value.

Oninitialized / oninitializedasync – component initialization

takeParameterCollectionThe state in the assigned to the component[Parameter]Property, these methods are executed. This andSetParametersAsyncThe usage of is the same, except that the state of the component can be used.

The method is executed only once when the component is first created. Skip this method if the parent later changes the parameters of the component.
Note: when the component is @ page and the blazor application navigates to a new URL that renders the same page, blazor will reuse the current object instance for that page. Because the object is the same instance, blazor will not call IDisposable Dispose, and its oninitialized method will not be executed again.

Onparametersset / onparameterssetasync – after parameter setting

If this is a new instance of the component, this method willOnInitializedAsyncImmediately thereafter. If it is an existing component that is being re rendered because its parent component is being re rendered, it will not be executedOnInitialized*Method, but inSetParametersAsyncExecute this method immediately after.

Onafterrender / onafterrenderasync – after component rendering

These two methods are used every time blazor regenerates the component
Execute when. This may be because the parent of the component is re rendered, the user interacts with the component (for example, a mouse click), or if the component executes its statehaschanged method to call the re rendering.

After understanding the life cycle of razor components, let’s continue to clean up the code

We add operation columns to the data table

See the effect below:

Next, we add an mdialog dialog box for adding and modifying
Just take the examples on the official website

In this process, we need to bind values to the dialog component and other components in the component using bind value.

Next, we add an onclick click event to the action column of the data table

Corresponding to edititem method in bound partial class

Let’s run it first to see the effect:

These two buttons correspond to each otherTwo buttons

Close is directly bound to the background close dialog method

The save method is used to modify the data and operate the DB. There is no demonstration here. Interested students can do the corresponding operations in combination with the business.

(4) Scenarios of using preset components to deal with common businesses

In our actual project, we will inevitably encounter the need for you to develop multiple modules or multiple management pages. In this way, each page will inevitably have some places that need you to repeat coding. Do you choose to copy the same code for each page or package a business component? There is no doubt that smart students will choose the latter. Of course, new students can take a look at the preset components provided by Masa blazor and use them immediately. Later, after entering the room, students can package the business components according to the current business.

Let’s take a look at the general header preset components:

Directly copy the code to see the effect:

When the length of data content in our data table is too long, we can use encapsulated dataPreset components:
See the effect:

It is easy to use and supports replication effects:

Of course, there are other commonly used preset components. Due to the limited space of this article, we only introduce the use of individual components, and the use methods are not bad. Interested students can go to the official website for reference.


The content of this article is only for students who are just beginning to learn. Students who are interested in packaging component skills and advanced usage of components can pay attention to the articles of other students in our same series or directly check the source code on the official website:

Using Masa blazor to develop a standard query table page and introduction of Packaging skills

Reference resources

Open source address






If you are interested in our Masa framework, whether it is code contribution, use or issue, please contact us