.NET 6 – dotnet new blazorserver

  1. สร้างโปรเจ็กส์
  2. หน้า Home
  3. หน้า Counter
  4. Add a component
  5. Set properties on the child component

1. สร้างโปรเจ็กส์

สร้างโฟลเดอร์ Blazor6

> mkdir Blazor6
> cd Blazor6

สร้างโปรเจ็กส์ด้วย Template แบบ Blazor Server App

> dotnet new blazorserver -o BlazorServer6
> cd .\BlazorServer6\

ถ้าสร้างด้วย VS 2022 เลือก Blazor Server App

run โปรแกรม

> dotnet run
Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:7249
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5020

run โปรแกรมแบบ Hot reload

> dotnet watch
dotnet watch ? Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload.
  ? Press "Ctrl + R" to restart.

หรือ

> dotnet watch run
dotnet watch ? Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload.
  ? Press "Ctrl + R" to restart.

2. หน้า Home

ไฟล์ Pages/Index.razor

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

บรรทัดที่ 9 เรียกใช้ SurveyPrompt พร้อมส่งค่า Title

ไฟล์ Shared/SurveyPrompt.razor

<div class="alert alert-secondary mt-4">
    <span class="oi oi-pencil me-2" aria-hidden="true"></span>
    <strong>@Title</strong>

    <span class="text-nowrap">
        Please take our
        <a target="_blank" class="font-weight-bold link-dark" href="https://go.microsoft.com/fwlink/?linkid=2149017">brief survey</a>
    </span>
    and tell us what you think.
</div>

@code {
    // Demonstrates how a parent component can supply parameters
    [Parameter]
    public string? Title { get; set; }
}

บรรทัดที่ 15 ประกาศตัวแปร Title
บรรทัดที่ 3 แสดงค่าตัวแปร Title

3. หน้า Counter

ไฟล์ Pages/Counter.razor

@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

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

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

4. Add a component

Each of the .razor files defines a UI component that can be reused.

ไฟล์ Pages/Index.razor

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<Counter />

บรรทัดที่ 11 Add a Counter component to the app’s homepage by adding a <Counter /> element

5. Set properties on the child component

Component parameters are specified using attributes or child content, which allow you to set properties on the child component. Define a parameter on the Counter component for specifying how much it increments with every button click:

ไฟล์ Pages/Counter.razor

@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

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

@code {
    private int currentCount = 0;

    [Parameter]
    public int IncrementAmount { get; set; } = 1;

    private void IncrementCount()
    {
        currentCount += IncrementAmount;
    }
}

ไฟล์ Pages/Index.razor

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<Counter IncrementAmount="10" />

ASP.NET Core Blazor

Blazor is a framework for building interactive client-side web UI with .NET:

  • Create rich interactive UIs using C# instead of JavaScript.
  • Share server-side and client-side app logic written in .NET.
  • Render the UI as HTML and CSS for wide browser support, including mobile browsers.
  • Integrate with modern hosting platforms, such as Docker.
  • Build hybrid desktop and mobile apps with .NET and Blazor.

Components

Blazor apps are based on components. A component in Blazor is an element of UI, such as a page, dialog, or data entry form.

Components are .NET C# classes built into .NET assemblies that:

The component class is usually written in the form of a Razor markup page with a .razor file extension. Components in Blazor are formally referred to as Razor components, informally as Blazor components. Razor is a syntax for combining HTML markup with C# code designed for developer productivity. Razor allows you to switch between HTML markup and C# in the same file with IntelliSense programming support in Visual Studio. Razor Pages and MVC also use Razor. Unlike Razor Pages and MVC, which are built around a request/response model, components are used specifically for client-side UI logic and composition.

Blazor Server

Blazor Server provides support for hosting Razor components on the server in an ASP.NET Core app. UI updates are handled over a SignalR connection.

The runtime stays on the server and handles:

  • Executing the app’s C# code.
  • Sending UI events from the browser to the server.
  • Applying UI updates to a rendered component that are sent back by the server.

The connection used by Blazor Server to communicate with the browser is also used to handle JavaScript interop calls.

Blazor Server runs .NET code on the server and interacts with the Document Object Model on the client over a SignalR connection

Blazor Server apps render content differently than traditional models for rendering UI in ASP.NET Core apps using Razor views or Razor Pages. Both models use the Razor language to describe HTML content for rendering, but they significantly differ in how markup is rendered.

When a Razor Page or view is rendered, every line of Razor code emits HTML in text form. After rendering, the server disposes of the page or view instance, including any state that was produced. When another request for the page occurs, the entire page is rerendered to HTML again and sent to the client.

Blazor WebAssembly

Blazor WebAssembly is a single-page app (SPA) framework for building interactive client-side web apps with .NET. Blazor WebAssembly uses open web standards without plugins or recompiling code into other languages. Blazor WebAssembly works in all modern web browsers, including mobile browsers.

Running .NET code inside web browsers is made possible by WebAssembly (abbreviated wasm). WebAssembly is a compact bytecode format optimized for fast download and maximum execution speed. WebAssembly is an open web standard and supported in web browsers without plugins.

WebAssembly code can access the full functionality of the browser via JavaScript, called JavaScript interoperability, often shortened to JavaScript interop or JS interop. .NET code executed via WebAssembly in the browser runs in the browser’s JavaScript sandbox with the protections that the sandbox provides against malicious actions on the client machine.

Blazor WebAssembly runs .NET code in the browser with WebAssembly.

When a Blazor WebAssembly app is built and run in a browser:

  • C# code files and Razor files are compiled into .NET assemblies.
  • The assemblies and the .NET runtime are downloaded to the browser.
  • Blazor WebAssembly bootstraps the .NET runtime and configures the runtime to load the assemblies for the app. The Blazor WebAssembly runtime uses JavaScript interop to handle DOM manipulation and browser API calls.

The size of the published app, its payload size, is a critical performance factor for an app’s usability. A large app takes a relatively long time to download to a browser, which diminishes the user experience. Blazor WebAssembly optimizes payload size to reduce download times:

  • Unused code is stripped out of the app when it’s published by the Intermediate Language (IL) Trimmer.
  • HTTP responses are compressed.
  • The .NET runtime and assemblies are cached in the browser.