Project structure of blade for server side

Time:2020-10-18

How cool is it to use C ා instead of JavaScript to do web applications?

Let’s talk about blazor today.

Blazor is a Web UI framework. This framework allows developers to use C ා to create web applications with fully interactive UI that can run in browsers.

It can be understood that this is a Vue / angular / react of C ා language. It can realize reusable Web UI together with HTML and CSS, and can share code and library with the server.

Blazor has all the functions of a modern web framework, including:

  • Component model for building composable UI

  • route

  • layout

  • Forms and validation

  • Dependency injection

  • JavaScript interoperability

  • Reload in browser in real time during development

  • Server side rendering

  • Full debugging of. Net in browser and IDE

  • Be able to pass asm.js Run on an earlier version of the (non web assembly) browser

Blazor has two hosting models:

  • Blazor WebAssembly (blazorwasm)
  • Blazor Server (blazorserver)

There is no big difference between the two models from the application level, but from the actual operation and deployment, the two models are quite different.

The application of blade web assembly runs on the browser and requires the browser to support web assembly. In other words, some early browsers didn’t support web assembly, so they couldn’t be used. At the same time, when an application runs for the first time, it needs to download the application and application dependencies and runtime locally, so there will be a load delay. However, this model can run all on the client side, making full use of the client resources and reducing the pressure on the server.

Blazor server, on the contrary, runs on the server and processes UI updates and events through signalr. As a result, it loads fast, takes full advantage of server capabilities, and runs early browsers. However, because the application needs to communicate with the server, it does not support offline work and the server is under great pressure.

There are so many simple differences. I will write another article about the details.

Today, we mainly talk about blade for server side, which is the blade server model described above.

    In order to prevent the reprint of the original website, the original link is added here: https://www.cnblogs.com/tiger-wang/p/13264415.html

1、 Create an empty project

Let’s first create an empty web project:

% dotnet new sln -o demoThe template "Solution File" was created successfully.% cd demo % dotnet new web -o demoThe template "ASP.NET Core Empty" was created successfully.Processing post-creation actions...Running 'dotnet restore' on demo/demo.csproj...  Determining projects to restore...  Restored /demo/demo/demo.csproj (in 148 ms).Restore succeeded.% dotnet sln add demo/demo.csproj Project `demo/demo.csproj` added to the solution.

Creation completed. Take a look at the directory structure:

% tree ..├── demo│   ├── Program.cs│   ├── Properties│   │   └── launchSettings.json│   ├── Startup.cs│   ├── appsettings.Development.json│   ├── appsettings.json│   └── demo.csproj└── demo.sln

This is our basic project. All subsequent projects will be modified and added on this basis.

2、 Add Blazer service

openStartup.csDocuments.

1. Modify configureservices

stayConfigureServicesAdd:

services.AddRazorPages();services.AddServerSideBlazor();

In these two lines of code,services.AddRazorPages()Yes, addRazorService.

RazorandBlazorThe name is similar, but it doesn’t matter in itself.RazorIs a server markup language similar toPHP

Add hereRazorBecause I’m used to itRazorThere is no particularity. If you are used to using MVC, you can change it hereservices.AddMvc()It’s the same.

Next lineservices.AddServerSideBlazor(), is the real content: addBlazor Server-SideService.

2. Modify configure

stayConfigureAdd:

app.UseStaticFiles();app.UseEndpoints(endpoints =>{    endpoints.MapBlazorHub();});

Among them,app.UseStaticFiles()Indicates that we will use static files. The file is required to be placed in thewwwrootDirectory, so you can also create the directory.

app.UseEndpoints, need to useBlazorRouting, so change toendpoints.MapBlazorHub()

It’s done here.

3. Join the route

Next, we need to establish a route. Create a directory in the projectPages。 This is the default single page directory for blade. And build one inside_Host.cshtml

@page "/"@namespace [email protected] *, Microsoft.AspNetCore.Mvc.TagHelpershtml><html lang="en"><head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width, initial-scale=1.0" />    <title>Demotitle>    <base href="~/" />head><body>    <app>        <component type="typeof(App)" render-mode="ServerPrerendered" />    app>    <script src="_framework/blazor.server.js">script>body>html>

And then in theStartup.csDocument’sConfigureAdd fallback route in:

app.UseEndpoints(endpoints =>{    endpoints.MapBlazorHub();    endpoints.MapFallbackToPage("/_Host");});

Put this here_Host.cshtmlRegistered as a fallback route, the function is to route all requests to the page of razor first, and then the page will make the final composition.

The required elements in this page are:

  • @Page, which defines the access point of this page
  • @Namespace, the namespace of the current page
  • Addtaghelper, tag help
  • Base, which defines the start of the route for this page
  • App, this sentence is the core of this page. We created it laterRazorThe page, in the form of a component, is placed in this location
  • Script, which is used to communicate with the server

In the above code, call to atypeof(App)This oneApp, is the routing component. Let’s create this route – create oneApp.razor

<Router AppAssembly="@typeof(Program).Assembly">    <Found Context="routeData">        <RouteView RouteData="@routeData" />    Found>    <NotFound>        Page Not found    NotFound>Router>

This template is used when dotnet is compiled.razorWith@pageProvides the specified routing template propertiesRouteAttributeAt the same time, it also reflects the aboveAppClass.

function. It appears in the browserPage Not Found。 This is where we areApp.razorIt means that we have not found any available routes.

3、 Create a page

Next, let’s create a pageindex.razor

@page "/"Hello, world!

This page is simple.

@Page, which tells the route that the URL of this page is/

Run it again, and we’ll see this page.

@Page defines the route of this page. There are several types of routing, I will list them briefly:

  • Direct routing:/page
  • Parameter Routing:/page/{page_id}
  • Constrained routing:/page/{page_id: int}

4、 Create a layout template

Let’s first create a directory in the projectSharedFor storing various components and templates. In the catalog, we create a layout template-MainLayout.razor

@using [email protected] LayoutComponentBase<div>    <h3>This is layouth3>div>@Body

There are several key points:

  • Layout templates must inherit from classesLayoutComponentBase
  • @The body defines the content location of the page that references the layout
  • The data type of the body isRenderFragment, inMicrosoft.AspNetCore.Components, need to be referenced

In fact, these operations are all C ා structure, only useRazorIn a different way

Now, let’s give it to youIndex.razorAdd layout template:

@using [email protected] MainLayout

As long asIndex.razorAdd these two lines to the top of the code. In these two lines:

@layoutIt defines which layout template this page uses; and@usingIt refers to the location of this template, which is in C ාusing

Run, we will see that the layout is added to the front of the page.

5、 Set default layout reference

The above example is to give the layout to a page.

We can also set the default layout template for all pages by changing the routing templateApp.razor

@using demo.Shared<Router AppAssembly="@typeof(Program).Assembly">    <Found Context="routeData">        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />    Found>    <NotFound>        Page Not Found    NotFound>Router>

The content of the document in front of the other party, this paragraph, is only in theRouteViewOne was added to theDefaultLayout

Now, layout templates are added to all pages by default.

6、 Set default namespace reference

In the above example, theApp.razorandIndex.razorWe all quoted themdemo.SharedNamespace.

Blazor provides a default file called_Imports.razorTo store all.razorCommon references in documents.

@using demo.Shared

We add the reference to this file and add the two above.razorRemove the reference in, and you’re done.

*Here’s a little more: layout templates can also be referenced here. The reference priority of layout template is: page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference > page reference >_ Imports.razor Quote > the App.razor quote.

The above is the project structure of blade server. After completing this structure, all the efforts are only on the razor page.

(end of full text)

The code for this article is in https://github.com/humornif/Demo-Code/tree/master/0017/demo

 


 

WeChat official account: Lao Wang Plus

Scanning the two-dimensional code, paying attention to the official account, can get the latest personal articles and content push.

The copyright of this article belongs to the author. Please keep this notice and the original link