Location>code7788 >text

NET8 Blazor from Start to Finish: (I) Key Concepts

Popularity:95 ℃/2024-08-02 10:34:55

catalogs
  • Blazor's key concepts
    • Project Templates
    • Razor Syntax
    • dependency injection
      • Injecting Configuration
    • HeadOutlet Component
    • @code Separation
    • Blazor Commissioning
    • CSS Isolation
    • Calling JavaScript

Recently in learning Blazor, in the B station to find a foreign course to watch and learn. Well, the original price of ¥ 1503 course, about more than 200 U.S. dollars, the course link is as follows:

Station B (large chapters divided into P - good for beginners):NET 8 Blazor from Start to Finish

Station B (small chapters divided into P- good for review):Blazor from beginner to master (Chinese subtitles)

Official website course:Blazor From Start to Finish

image

Blazor's key concepts

This article introduces the key concepts of Blazor, and each point is accompanied by references found during the learning process. The text removes some common sense or poorly articulated content, such as hot reloading, components and pages, and so on.

Project Templates

Project development of common template configuration items are as follows, other configurations can also be all tried to observe the difference:
image

Auto Interaction: Blazor Server is used initially, and WebAssembly is used to automate interactive client-side rendering on subsequent visits, see details atA First Look at .NET8 Blazor's Auto Render Mode

Razor Syntax

consultation Razor Syntax Reference for CoreThe main focus in the early stages is to understand the following key grammars:

  • Implicit Razor Expressions: starts with @ followed by C# code
<p>@</p>
<p>@(2016)</p>
  • Explicit Razor Expressions: consists of the @ symbol and parentheses
<p>Last week this time: @( - (7))</p>
  • @code block: Allows Razor components to add C# members (fields, properties and methods) to components
@code {
    // C# members (fields, properties, and methods)
}
  • Loop and Conditional StatementsAs@for@if etc., written directly in the page
@for (var i = 0; i < ; i++)
{
    var person = people[i];
    <p>Name: @</p>
    <p>Age: @</p>
}

@if (value % 2 == 0)
{
    <p>The value was even.</p>
}

dependency injection

consultationInjecting dependencies into Blazor components
exist(Project Bootstrap Program) Register dependencies in the

<DemoDependency>();.
// Other patterns for registering dependencies...

For Blazor components, there are two ways to indicate which dependencies our component uses:

//1.exist Razor tagged with
@inject IToDoApi ToDoApi
@inject ISomeServiceType AnotherService

//2.exist C# coding
@code
{
  [Inject]
  private IYetAnotherServiceType PropertyInjectedDependency { get; set; }
}

Injecting Configuration

consultation Core Blazor Configuration , which configures the priority level:User Confidential > appsettings.{Environment}.json >

Configure the connection string in:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Default": "The connection string comes from the"
  }
}

Introduces configuration dependencies in the component:

@page "/"
@inject IConfiguration config

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>
<h2>@("Default")</h2>

IConfiguration is registered by default, you don't need to write another code to register, you can use it directly.

HeadOutlet Component

Instead of the entire page being reloaded when switching pages, only the root component is actually reloaded. (used form a nominal expression)<Routes /> be re-rendered. This type of rendering is not good for SEO and can be done using theHeadOutlet component to control the content of the <head> element for optimization.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="bootstrap/" />
    <link rel="stylesheet" href="" />
    <link rel="stylesheet" href="" />
    <link rel="icon" type="image/png" href="" />
    <HeadOutlet />
</head>

<body>
    <Routes />
    <script src="_framework/"></script>
</body>

</html>

consultationControlling Content in Core Blazor Applications, specifies the title and description of a page:

@page "/control-head-content"

<PageTitle>@title</PageTitle>
<p>Title: @title</p>
<p>Description: @description</p>

<HeadContent>
    <meta name="description" content="@description">
</HeadContent>

@code {
    private string description = "This description is set by the component.";
    private string title = "Control <head> Content";
}
  • utilizationPageTitle component specifies the page title so that the HTML <title> element can be rendered to the HeadOutlet component.
  • utilizationHeadContent component specifies the content of the <head> element that provides content for the HeadOutlet component.

Note that if page B is used in page A, then the PageTitle of page B will overwrite the PageTitle of page A. So, theDon't put a PageTitle if the component is not to be used as a page. Up.

@code Separation

Blazor can support adding cs code inside the razor file, but the code becomes especially troublesome once it becomes complex. In fact, this part of the code is actually separated at compile time, we can also manually separate them before compilation.

right clickcode SelectionRapid operation and reconfiguration Then selectExtracting blocks into code hiding
image

The result is as follows, where ① is just a shortcut to ②:
image

The above is using the automatic separation feature of VS, but you can also use the manual way to separate. Refer toC# Blazor Learning Notes(4):Blazor Code Separation, pay attention to the following points:

  • Right-click directly on the parent directory of the razor component to add aPartial Local Classes
  • new categoryThe class name isThis is how you hook up to the component.

: code
: css style

After code separation, dependencies also need to be changed to property injection:

using ;

namespace ;

public partial class Demo
{
    // existrazorIt looks like this in the component @inject IConfiguration config
    [Inject]
    protected IConfiguration config { get; set; }=default!;

    private string? GetConnectionString()
    {
        return ("Default");
    }
}

Blazor Commissioning

There's not much to say about debugging, just break points, run single-steps, and monitor variable values in VS as normal.Debugging Core Applications

CSS Isolation

CSS isolation canLimiting CSS Scope to Razor Componentsto simplify CSS and avoid conflicts with other components or libraries, but overuse can also make CSS tracking difficult.

consultation Core Blazor CSS Isolation , in the same folder as the component, create a. file, which is the same as the component's.razor The name of the file matches. For example, for component creates a Documentation:

h1 {
    color:red;
}

At generation time Blazor overrides the CSS selectors to match the markup rendered by the component, the rewritten CSS styles are bundled and generated as static assets, and by default table styles are referenced in the markup:

<! -- {ASSEMBLY NAME} The placeholder is the assembly name of the project ! -->
<link href="{ASSEMBLY NAME}." rel="stylesheet"> <link href="{ASSEMBLY NAME}.

In the bundled documents, theEach component is associated with a scope identifier. For each component that has a style, the HTML attribute is appended with theFormat b-{STRING}, where the {STRING} placeholder is a ten-character string generated by the frame. Identifiers are unique to each application.

In the rendered Counter component, Blazor appends the range identifier to the h1 element:

<h1 b-zdeg3nv67a="">Counter</h1>

image

Note: If the CSS doesn't work, you need to clear your browser's cache.

Calling JavaScript

The js file can be placed in the wwwroot directory or associated with a specific component, cf.
Load scripts from an external JavaScript file (.js) that is juxtaposed with a component Adds juxtaposed js files to the Counter component:

//
export function displayCount(count) {
    alert('The count is' + count);
}

export function createMessage(count) {
    return 'The count is' + count;
}

Using the Razor Component for Blazor Applications. Extensions are juxtaposed with JS files (see CSS Isolation section) and can be publicly addressed by the path to the file in the project.{PATH}/{COMPONENT}.

  • The placeholder {PATH} is the path to the component.
  • The placeholder {COMPONENT} is the component

Modify the code of the Counter component to call the js function:

@page "/counter"
@rendermode InteractiveAuto
@inject IJSRuntime JSRuntime

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>
<h2>@subMessage</h2>
<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary"  @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;
    private string subMessage = "";
    private IJSObjectReference? jsModule;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            jsModule = await <IJSObjectReference>("import", "./Pages/");
        }    
    }
    private async Task IncrementCount()
    {
        currentCount++;
        await ("displayCount", currentCount);
        subMessage = await <string>("createMessage", currentCount);
    }
}
  • @inject IJSRuntime JSRuntime: Injects the IJSRuntime interface for interacting with client-side JavaScript.
  • IJSObjectReference? jsModule: Save references to JavaScript modules

  • <IJSObjectReference>
    : Load a JavaScript module and save its reference

In real projects, try not to use js to control the DOM, but use Blazor components, because the two may conflict.