Getting started with MASA Blazor is enough

1. What is Blazor? What are the advantages?

Introduction to ASP.NET Core Blazor

Blazor is a framework for generating interactive client-side web UIs using Blazor:

  1. Use C# instead of JavaScript to create informative, interactive UIs.
  2. Share server-side and client-side application logic written in .NET.
  3. Render UI to HTML and CSS to support many browsers, including mobile browsers.
  4. Integrate with modern hosting platforms like Docker.

Blazor Advantages:

  1. 使用 C# 代替 JavaScript 来编写代码。
  2. 利用现有的 .NET 库生态系统。
  3. 在服务器和客户端之间共享应用逻辑。
  4. 受益于 .NET 的性能、可靠性和安全性。
  5. 在 Windows、Linux 和 macOS 上使用 Visual Studio 保持高效工作。
  6. 以一组稳定、功能丰富且易用的通用语言、框架和工具为基础来进行生成。

2. Why choose MASA Blazor? What can it be used for?

MASA Blazor is a UI component library based on Blazor Component and Material Design. dotNET developers do not need to know javascript to develop an enterprise-level back-end system. Advantages of MASA Blazor:

  • Rich components: Contains the basic components restored by Vuetify 1:1, as well as many practical preset components and .Net deep integration functions, including Url, breadcrumbs, navigation triple linkage, advanced search, i18n, etc.
  • UI design language: The design style is modern, and the UI multi-end experience design is excellent.
  • Easy to get started: Rich and detailed start-up documentation, free video tutorials (in production).
  • Active community encouragement: users participate in real-time interaction, make contributions to join us, and build the most open open source community.
  • Long-term support: Full-time team maintenance with enterprise-level support.
  • Professional example: MASA Blazor Pro offers preset layouts for many common scenarios.

MASA Blazor Pro preset layout example:

See if there are students here who are interested in this! So how is such a layout page constructed? Can we build a layout like this ourselves? Hey-hey! Don't worry, we'll see below.

3. Create your first Blazor program using the MASA Blazor template

1. First install the Masa.Template template

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

(2) Install the Masa.Template template, including all project templates of the MASA series dotnet new --install Masa.Template

2. Create a project

dotnet new masab -o MasaBlazorApp defaults to Server mode. You can create a WebAssembly mode project with the parameter --Mode WebAssembly

3. Configure MASA Blazor (because I used a template here, the following configurations have been configured for us in the template, and you can directly dotnet run after installing the template; students who have not installed the template, follow the steps below to configure)

(1) Install NuGet package

dotnet add package Masa.Blazor

(2) Introduce resource files (I am Blazor Server here)

Introduce resource files in Pages/_Layout.cshtml

(3) Inject related services

Add Masa.Blazor related services in Program.cs

builder.Services.AddMasaBlazor();

(4) Modify the _Imports.razor file and add the following:

  @using Masa.Blazor

(5) Running the project

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

3. Configure the project with MASA Blazor components

Example:

(1) Introduction to Blazor application structure

First, let's take a look at the Blazor project structure and analyze the role of the main files. (The concept definition is relatively boring. Students who want to experience it directly can skip this part and start practicing directly, but it is not recommended to do so. There is a saying that "Sharpening a knife does not cut woodwork by mistake".

Program.cs

Entry points for Blazor server applications are defined in the Program.cs file, just like console applications. When the application executes, it creates and runs a web host instance with web application-specific defaults. The web host manages the lifecycle of the Blazor server application and sets up host-level services.

In the Blazor server app , the Program.cs file shown is used to set the endpoint for the live connection that Blazor uses between the client browser and the server. In a Blazor WebAssembly app , the Program.cs file defines the app's root component and where it renders:

In the Program.cs file, we first focus on a few points:

1. In dependency injection, because we use Razor to implement mixed coding of C# and html and we use Blazor of ServerSide, the injection code is as follows: The middleware is as follows:

_Host.cshtml

In a Blazor server application, the host page for the root component is defined in the _Host.cshtml file. This file defines a Razor Page, not a component. Razor Pages uses Razor syntax to define server-addressable pages.

In the Program.cs file, it will automatically go to the _Host.cshtml file we configured to find the root component. 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 documentation:

App.razor The root component of the Blazor application, which usually contains the Router component to handle routing in Blazor

So what are the functions of these parameters in the Router component, such as AppAssembly, Found, and NotFound?

By reading the official documentation we can find:

The Router component discovers routable components in the specified AppAssembly and AdditionalAssemblies (optional). When the browser is navigating, if a route matches the address, the Router will intercept the navigation and render the content of its Found parameter and the extracted RouteData, otherwise, the Router will render its NotFound parameter.

The RouteView component is responsible for rendering the matching components specified by RouteData and their layout (if any). If the matching component has no layout, the optionally specified DefaultLayout is used.

The LayoutView component renders its child content within the specified layout

That is to say, after we configure the route of the .razor page, the Router component will match the route with the address when the browser navigates. If it can be matched, the Router will intercept the navigation and render the matching component and layout specified by its Found parameter. (We specify the MainLayout layout page here), otherwise, the NotFound parameter is rendered.

_Layout.cshtml

In the previous _Host.cshtml file, we specified that the _Layout.cshtml layout page is enabled by default. _Layout.cshtml is the host page of the Blazor application (equivalent to a root page layout file), which contains the application's initialization HTML and its components, which Makes it easier to maintain the look and feel of all our page layouts.

MainLayout.razor

In Blazor, use layout components to handle page layout. Layout components inherit from LayoutComponentBase, which defines a single Body property of type RenderFragment that can be used to render the content of the page.

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

Well, there is a lot of nonsense. The main structural concepts of the it .

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

In the above page display, we see three menu pages. These pages are configured with the corresponding routing Home page corresponding to Index.razor and routing as "/"

The corresponding page of Counter is Counter.razor, and the route is "/counter"

The Fetch Data page corresponds to the FetchData.razor page route, and the route is "/fetchdata" We can see the configuration in the Shared/MainLayout.razor page.

Next, we directly move to the MASA Blazor official website address to find the component examples we need:

We can directly copy the sample code to the MAppBar component in the Shared/MainLayout.razor page

dotnet run to see the effect

Next, we find the Navigation drawers component in the MASA Blazor component library, and copy the razor page code and C# code to the <MNavigationDrawer> component.

We modify the code slightly

dotnet run to see the effect

Next, let's implement the dynamic menu bar scaling function to find the mini mode of the Navigation drawers component

Next let's modify our code

dotnet run to see the effect

Doesn't it feel super easy! Of course, this is just an introductory way of writing. Interested students can try it out to unlock the usage and writing of more components.

(3) Use DataTable, Dialog and other components to implement a basic data interaction page

First, we initialize Fetch.razor, leaving only one of the simplest <MDataTable> components

The DataTable component needs to bind at least one Headers (header) and data source, so the next step is to define Headers and Items (you can actually call the API to get data, the default dead data here is only for reference) Let's build a Fetch.razor page first. Partial class, which defines part of the code

dotnet run to see the effect

In the above code screenshot, you will find that we use the OnInitializedAsync() method, so what is this method used for? Speaking of this problem, we need to first understand the life cycle of Razor components ASP.NET Core Razor component life cycle

First look at a Component lifecycle diagram (component lifecycle diagram)

SetParametersAsync - when setting parameters

This method is executed whenever the parent renders. Parameters passed into the component are included in ParameterView. This is a good time to make an asynchronous call to the server (for example) based on the state of the incoming component. When called in an override, base.SetParametersAsync(Parameters)a property of the component is [Parameter]assigned a value. It is also the correct place to specify default parameter values.

OnInitialized / OnInitializedAsync - Component initialization

These methods are executed after assigning the state in the component to a property of the ParameterCollectioncomponent . [Parameter]This is SetParametersAsyncthe same usage as , except that the state of the component can be used.

This method is executed only once when the component is first created. This method is skipped if the parent later changes the component's parameters. 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 on the object, nor will it execute its OnInitialized method again.

OnParametersSet / OnParametersSetAsync - after parameters are set

If this is a new instance of the component, this method will OnInitializedAsyncexecute immediately after. If it's an existing component that is re-rendering because its parent component is re-rendering, the method will not be executed OnInitialized*, but SetParametersAsyncthis method will be executed immediately after.

OnAfterRender / OnAfterRenderAsync - After the component is rendered

These two methods are executed each time Blazor regenerates the component's RenderTree . This could be because the component's parent re-renders, the user interacts with the component (for example, a mouse click), or if the component executes its StateHasChanged method to invoke the re-render.

After understanding the life cycle of Razor components, let's continue to code

We add an action column to the data table

Take a look at the effect: Next, we will add an MDialog dialog box for adding and modifying operations and directly take the example from the official website.

In this process, we need to use Bind-Value (two-way binding) to bind the value to the Dialog component and other components in the component.

Next, we add the OnClick click event to the Action column of the data table

Corresponding to the EditItem method in the binding partial class

Let's run it first to see the effect:

These two buttons correspond to the two Buttons of <MCardActions>

Close directly binds the background close Dialog method

The Save method is used to finally modify the data and other methods of operating the DB, which will not be demonstrated here. Interested students can do the corresponding operations in combination with the business.

(4) Use preset components to deal with common business scenarios

In our actual project, it is inevitable that you will need to develop multiple modules or multiple management pages. In this way, each page will inevitably have some places that require you to repeatedly code. Then you choose to copy one page per page. Do you want to copy the same code or choose to encapsulate a business component? There is no doubt that smart students will choose the latter. Of course, newcomers can first take a look at the pre-built components provided by MASA Blazor, which can be used immediately. After entering the classroom, students can package the business components according to the current business.

Let's take a look at the general page header preset components: copy the code directly to see the effect:

When the data content in our data table is too long, we can use the packaged <CopyableText> preset component: See the effect:

The method of use is very simple and supports copying effects: of course, there are other commonly used preset components. Due to the limited space of this article, I only introduce the use of individual components, and the usage methods are quite similar. Interested students can go to the official website.

end

The content introduced in this article is only aimed at the students who are just getting started. Students who are interested in packaging component skills and advanced usage of components can follow the articles of other students in the same series or go directly to the official website to view the source code:

Using MASA Blazor to develop a standard query form page and introduction to packaging skills

Reference resources

open source address

MASA.BuildingBlocks:https://github.com/masastack/MASA.BuildingBlocks

MASA.Contrib:https://github.com/masastack/MASA.Contrib

MASA.Utils:https://github.com/masastack/MASA.Utils

MASA.EShop :https://github.com/masalabs/MASA.EShop

MASA.Blazor:https://github.com/BlazorComponent/MASA.Blazor

If you are interested in our MASA Framework, whether it is code contribution, use, issue, please contact us

16373211753064.png

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324214316&siteId=291194637