AspNetCore.Docs/aspnetcore/blazor/fundamentals/index.md

260 lines
19 KiB
Markdown
Raw Normal View History

---
title: ASP.NET Core Blazor fundamentals
author: guardrex
description: Learn foundational concepts of the Blazor application framework.
monikerRange: '>= aspnetcore-3.1'
ms.author: riande
ms.custom: mvc
2024-11-18 21:14:57 +08:00
ms.date: 11/12/2024
uid: blazor/fundamentals/index
---
# ASP.NET Core Blazor fundamentals
[!INCLUDE[](~/includes/not-latest-version.md)]
2023-04-04 23:06:06 +08:00
*Fundamentals* articles provide guidance on foundational Blazor concepts. Some of the concepts are connected to a basic understanding of *Razor components*, which are described further in the next section of this article and covered in detail in the *Components* articles.
2023-11-15 00:46:25 +08:00
:::moniker range=">= aspnetcore-8.0"
## Static and interactive rendering concepts
Razor components are either *statically* rendered or *interactively* rendered.
*Static* or *static rendering* is a server-side scenario that means the component is rendered without the capacity for interplay between the user and .NET/C# code. JavaScript and HTML DOM events remain unaffected, but no user events on the client can be processed with .NET running on the server.
*Interactive* or *interactive rendering* means that the component has the capacity to process .NET events via C# code. The .NET events are either processed on the server by the ASP.NET Core runtime or in the browser on the client by the WebAssembly-based Blazor runtime.
> [!IMPORTANT]
> When using a Blazor Web App, most of the Blazor documentation example components ***require*** interactivity to function and demonstrate the concepts covered by the articles. When you test an example component provided by an article, make sure that either the app adopts global interactivity or the component adopts an interactive render mode.
2023-11-15 00:46:25 +08:00
More information on these concepts and how to control static and interactive rendering is found in the <xref:blazor/components/render-modes> article later in the Blazor documentation.
:::moniker-end
2024-08-17 03:05:42 +08:00
## Client and server rendering concepts
Throughout the Blazor documentation, activity that takes place on the user's system is said to occur *on the client* or *client-side*. Activity that takes place on a server is said to occur *on the server* or *server-side*.
The term *rendering* means to produce the HTML markup that browsers display.
2024-09-16 22:27:18 +08:00
* **Client-side rendering (CSR)** means that the final HTML markup is generated by the .NET WebAssembly runtime on the client. No HTML for the app's client-generated UI is sent from a server to the client for this type of rendering. User interactivity with the page is assumed. There's no such concept as *static* client-side rendering. CSR is assumed to be interactive, so "*interactive* client-side rendering" and "*interactive* CSR" aren't used by the industry or in the Blazor documentation.
2024-08-17 03:05:42 +08:00
* **Server-side rendering (SSR)** means that the final HTML markup is generated by the ASP.NET Core runtime on the server. The HTML is sent to the client over a network for display by the client's browser. No HTML for the app's server-generated UI is created by the client for this type of rendering. SSR can be of two varieties:
* **Static SSR**: The server produces static HTML that doesn't provide for user interactivity or maintaining Razor component state.
* **Interactive SSR**: Blazor events permit user interactivity and Razor component state is maintained by the Blazor framework.
* **Prerendering** is the process of initially rendering page content on the server without enabling event handlers for rendered controls. The server outputs the HTML UI of the page as soon as possible in response to the initial request, which makes the app feel more responsive to users. Prerendering can also improve [Search Engine Optimization (SEO)](https://developer.mozilla.org/docs/Glossary/SEO) by rendering content for the initial HTTP response that search engines use to calculate page rank. Prerendering is always followed by final rendering, either on the server or the client.
## Razor components
2022-07-12 18:58:55 +08:00
Blazor apps are based on *Razor components*, often referred to as just *components*. A *component* is an element of UI, such as a page, dialog, or data entry form. Components are .NET C# classes built into [.NET assemblies](/dotnet/standard/assembly/).
*Razor* refers to how components are usually written in the form of a [Razor](xref:mvc/views/razor) markup page for client-side UI logic and composition. Razor is a syntax for combining HTML markup with C# code designed for developer productivity. Razor files use the `.razor` file extension.
Although some Blazor developers and online resources use the term "Blazor components," the documentation avoids that term and universally uses "Razor components" or "components."
Blazor documentation adopts several conventions for showing and discussing components:
2024-09-19 00:54:04 +08:00
* Generally, examples adhere to ASP.NET Core/C# coding conventions and engineering guidelines. For more information see the following resources:
* [ASP.NET Core framework engineering guidelines (`dotnet/aspnetcore` GitHub repository)](https://github.com/dotnet/aspnetcore/wiki/Engineering-guidelines)
* [C# Coding Conventions (C# guide)](/dotnet/csharp/fundamentals/coding-style/coding-conventions)
* Project code, file paths and names, project template names, and other specialized terms are in United States English and usually code-fenced.
* Components are usually referred to by their C# class name (Pascal case) followed by the word "component." For example, a typical file upload component is referred to as the "`FileUpload` component."
* Usually, a component's C# class name is the same as its file name.
* Routable components usually set their relative URLs to the component's class name in kebab-case. For example, a `FileUpload` component includes routing configuration to reach the rendered component at the relative URL `/file-upload`. Routing and navigation is covered in <xref:blazor/fundamentals/routing>.
* When multiple versions of a component are used, they're numbered sequentially. For example, the `FileUpload3` component is reached at `/file-upload-3`.
2024-09-19 00:54:04 +08:00
* [Razor directives](xref:mvc/views/razor#directives) at the top of a component definition (`.razor file`) are placed in the following order: `@page`, `@rendermode` (.NET 8 or later), `@using` statements, other directives in alphabetical order.
2024-09-12 01:48:54 +08:00
* Although not required for `private` members, access modifiers are used in article examples and sample apps. For example, `private` is stated for declaring a field named `maxAllowedFiles` as `private int maxAllowedFiles = 3;`.
* [Component parameter](xref:blazor/components/index#component-parameters) values lead with a [Razor reserved `@` symbol](xref:mvc/views/razor#razor-syntax), but it isn't required. Literals (for example, boolean values), keywords (for example, `this`), and `null` as component parameter values aren't prefixed with `@`, but this is also merely a documentation convention. Your own code can prefix literals with `@` if you wish.
2024-09-19 00:54:04 +08:00
* C# classes use the [`this` keyword](/dotnet/csharp/language-reference/keywords/this) and avoid prefixing fields with an underscore (`_`) that are assigned to in constructors, which differs from the [ASP.NET Core framework engineering guidelines](https://github.com/dotnet/aspnetcore/wiki/Engineering-guidelines).
* In examples that use [primary constructors (C# 12 or later)](/dotnet/csharp/whats-new/tutorials/primary-constructors), primary constructor parameters are typically used directly by class members.
In article examples, code lines are split to reduce horizontal scrolling. These breaks don't affect execution but can be removed when pasting into your project.
2024-09-19 00:54:04 +08:00
Additional information on Razor component syntax is provided in the *Razor syntax* section of <xref:blazor/components/index#razor-syntax>.
The following is an example counter component and part of an app created from a Blazor project template. Detailed components coverage is found in the *Components* articles later in the documentation. The following example demonstrates component concepts seen in the *Fundamentals* articles before reaching the *Components* articles later in the documentation.
`Counter.razor`:
2024-10-18 20:02:14 +08:00
:::moniker range=">= aspnetcore-9.0"
The component assumes that an interactive render mode is inherited from a parent component or applied globally to the app.
:::code language="razor" source="~/../blazor-samples/9.0/BlazorSample_BlazorWebApp/Components/Pages/Counter.razor":::
:::moniker-end
:::moniker range=">= aspnetcore-8.0 < aspnetcore-9.0"
2023-11-15 00:46:25 +08:00
2023-12-22 19:25:19 +08:00
The component assumes that an interactive render mode is inherited from a parent component or applied globally to the app.
2023-12-20 23:39:31 +08:00
2023-12-21 22:23:23 +08:00
:::code language="razor" source="~/../blazor-samples/8.0/BlazorSample_BlazorWebApp/Components/Pages/Counter.razor":::
2023-11-15 00:46:25 +08:00
:::moniker-end
:::moniker range=">= aspnetcore-7.0 < aspnetcore-8.0"
:::code language="razor" source="~/../blazor-samples/7.0/BlazorSample_WebAssembly/Pages/Counter.razor":::
:::moniker-end
:::moniker range=">= aspnetcore-6.0 < aspnetcore-7.0"
:::code language="razor" source="~/../blazor-samples/6.0/BlazorSample_WebAssembly/Pages/Counter.razor":::
:::moniker-end
:::moniker range=">= aspnetcore-5.0 < aspnetcore-6.0"
:::code language="razor" source="~/../blazor-samples/5.0/BlazorSample_WebAssembly/Pages/Counter.razor":::
:::moniker-end
:::moniker range="< aspnetcore-5.0"
:::code language="razor" source="~/../blazor-samples/3.1/BlazorSample_WebAssembly/Pages/Counter.razor":::
:::moniker-end
The preceding `Counter` component:
* Sets its route with the `@page` directive in the first line.
* Sets its page title and heading.
* Renders the current count with `@currentCount`. `currentCount` is an integer variable defined in the C# code of the `@code` block.
* Displays a button to trigger the `IncrementCount` method, which is also found in the `@code` block and increases the value of the `currentCount` variable.
2023-11-15 00:46:25 +08:00
:::moniker range=">= aspnetcore-8.0"
## Render modes
Articles in the *Fundamentals* node make reference to the concept of *render modes*. This subject is covered in detail in the <xref:blazor/components/render-modes> article in the *Components* node, which appears after the *Fundamentals* node of articles.
For the early references in this node of articles to render mode concepts, merely note the following at this time:
Every component in a Blazor Web App adopts a *render mode* to determine the hosting model that it uses, where it's rendered, and whether or not it's rendered statically on the server, rendered with for user interactivity on the server, or rendered for user interactivity on the client (usually with prerendering on the server).
Blazor Server and Blazor WebAssembly apps for ASP.NET Core releases prior to .NET 8 remain fixated on *hosting model* concepts, not render modes. Render modes are conceptually applied to Blazor Web Apps in .NET 8 or later.
The following table shows the available render modes for rendering Razor components in a Blazor Web App. Render modes are applied to components with the `@rendermode` directive on the component instance or on the component definition. It's also possible to set a render mode for the entire app.
Name | Description | Render location | Interactive
---- | ----------- | :-------------: | :---------:
Static Server | Static server-side rendering (static SSR) | Server | <span aria-hidden="true"></span><span class="visually-hidden">No</span>
Interactive Server | Interactive server-side rendering (interactive SSR) using Blazor Server | Server | <span aria-hidden="true">✔️</span><span class="visually-hidden">Yes</span>
Interactive WebAssembly | Client-side rendering (CSR) using Blazor WebAssembly&dagger; | Client | <span aria-hidden="true">✔️</span><span class="visually-hidden">Yes</span>
Interactive Auto | Interactive SSR using Blazor Server initially and then CSR on subsequent visits after the Blazor bundle is downloaded | Server, then client | <span aria-hidden="true">✔️</span><span class="visually-hidden">Yes</span>
&dagger;Client-side rendering (CSR) is assumed to be interactive. "*Interactive* client-side rendering" and "*interactive* CSR" aren't used by the industry or in the Blazor documentation.
2023-11-15 00:46:25 +08:00
The preceding information on render modes is all that you need to know to understand the *Fundamentals* node articles. If you're new to Blazor and reading Blazor articles in order down the table of contents, you can delay consuming in-depth information on render modes until you reach the <xref:blazor/components/render-modes> article in the *Components* node.
:::moniker-end
2023-07-21 20:10:18 +08:00
## Document Object Model (DOM)
References to the *Document Object Model* use the abbreviation *DOM*.
2023-07-21 20:10:18 +08:00
For more information, see the following resources:
* [Introduction to the DOM (MDN documentation)](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction)
* [Level 1 Document Object Model Specification (W3C)](https://www.w3.org/TR/WD-DOM/)
## Subset of .NET APIs for Blazor WebAssembly apps
A curated list of specific .NET APIs that are supported on the browser for Blazor WebAssembly isn't available. However, you can manually [search for a list of .NET APIs annotated with `[UnsupportedOSPlatform("browser")]`](https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/PlatformAttributes.cs,34041602e232c616,references) to discover .NET APIs that aren't supported in WebAssembly.
[!INCLUDE[](~/includes/aspnetcore-repo-ref-source-links.md)]
For more information, see the following resources:
* [Class libraries: Client-side browser compatibility analyzer](xref:blazor/components/class-libraries#client-side-browser-compatibility-analyzer)
* [Annotating APIs as unsupported on specific platforms (`dotnet/designs` GitHub repository](https://github.com/dotnet/designs/blob/main/accepted/2020/platform-exclusion/platform-exclusion.md#build-configuration-for-platforms)
## Sample apps
Documentation sample apps are available for inspection and download:
[Blazor samples GitHub repository (`dotnet/blazor-samples`)](https://github.com/dotnet/blazor-samples)
Locate a sample app by first selecting the version folder that matches the version of .NET that you're working with.
:::moniker range=">= aspnetcore-8.0"
Samples apps in the repository:
* Blazor Web App
* Blazor WebAssembly
* Blazor Web App with EF Core (<xref:blazor/blazor-ef-core>)
* Blazor Web App with SignalR (<xref:blazor/tutorials/signalr-blazor>)
* Two Blazor Web Apps and a Blazor WebAssembly app for calling web (server) APIs (<xref:blazor/call-web-api>)
* Blazor Web App with OIDC (BFF and non-BFF patterns) (<xref:blazor/security/blazor-web-app-oidc>)
* Blazor WebAssembly scopes-enabled logging (<xref:blazor/fundamentals/logging#client-side-log-scopes>)
* Blazor WebAssembly with ASP.NET Core Identity (<xref:blazor/security/webassembly/standalone-with-identity/index>)
* .NET MAUI Blazor Hybrid app with a Blazor Web App and a shared UI provided by a Razor class library (RCL) (<xref:blazor/hybrid/tutorials/maui-blazor-web-app>)
:::moniker-end
:::moniker range="< aspnetcore-8.0"
2023-12-20 23:39:31 +08:00
The sample repo contains two types of samples:
* Snippet sample apps provide the code examples that appear in articles. These apps compile but aren't necessarily runnable apps. These apps are useful for merely obtaining example code that appears in articles.
* Samples apps to accompany Blazor articles compile and run for the following scenarios:
* Blazor Server with EF Core
* Blazor Server and Blazor WebAssembly with SignalR
* Blazor WebAssembly scopes-enabled logging
:::moniker-end
2024-10-31 20:43:29 +08:00
For more information and a list of the samples in the repository, see the [Blazor samples GitHub repository README.md file](https://github.com/dotnet/blazor-samples).
The ASP.NET Core repository's Basic Test App is also a helpful set of samples for various Blazor scenarios:
[`BasicTestApp` in ASP.NET Core reference source (`dotnet/aspnetcore`)](https://github.com/dotnet/aspnetcore/tree/main/src/Components/test/testassets/BasicTestApp)
[!INCLUDE[](~/includes/aspnetcore-repo-ref-source-links.md)]
To download the sample apps:
* Download the [Blazor samples repository](https://github.com/dotnet/blazor-samples) ZIP file.
* Unzip the file.
2022-09-22 03:03:13 +08:00
## Byte multiples
.NET byte sizes use metric prefixes for non-decimal multiples of bytes based on powers of 1024.
| Name (abbreviation) | Size | Example |
| ------------------- | ----------------------- | -------------------------- |
2022-10-09 23:53:26 +08:00
| Kilobyte (KB) | 1,024 bytes | 1 KB = 1,024 bytes |
2022-09-22 03:03:13 +08:00
| Megabyte (MB) | 1,024<sup>2</sup> bytes | 1 MB = 1,048,576 bytes |
| Gigabyte (GB) | 1,024<sup>3</sup> bytes | 1 GB = 1,073,741,824 bytes |
## Support requests
Only documentation-related issues are appropriate for the `dotnet/AspNetCore.Docs` repository. ***For product support, don't open a documentation issue.*** Seek assistance through one or more of the following support channels:
* [Stack Overflow (tagged: `blazor`)](https://stackoverflow.com/questions/tagged/blazor)
2023-01-11 23:44:58 +08:00
* [General ASP.NET Core Slack Team](https://join.slack.com/t/aspnetcore/shared_invite/zt-1mv5487zb-EOZxJ1iqb0A0ajowEbxByQ)
* [Blazor Gitter](https://gitter.im/aspnet/Blazor)
For a potential bug in the framework or product feedback, open an issue for the ASP.NET Core product unit at [`dotnet/aspnetcore` issues](https://github.com/dotnet/aspnetcore/issues). Bug reports usually ***require*** the following:
* **Clear explanation of the problem**: Follow the instructions in the GitHub issue template provided by the product unit when opening the issue.
* **Minimal repro project**: Place a project on GitHub for the product unit engineers to download and run. Cross-link the project into the issue's opening comment.
For a potential problem with a Blazor article, open a documentation issue. To open a documentation issue, use the **Open a documentation issue** feedback link at the bottom of the article. Metadata added to your issue provides tracking data and automatically pings the author of the article. If the subject was discussed with the product unit prior to opening the documentation issue, place a cross-link to the engineering issue in the documentation issue's opening comment.
For problems or feedback on Visual Studio, use the [**Report a Problem**](/visualstudio/ide/how-to-report-a-problem-with-visual-studio) or [**Suggest a Feature**](/visualstudio/ide/suggest-a-feature) gestures from within Visual Studio, which open internal issues for Visual Studio. For more information, see [Visual Studio Feedback](https://developercommunity.visualstudio.com/home).
For problems with Visual Studio Code, ask for support on community support forums. For bug reports and product feedback, open an issue on the [`microsoft/vscode` GitHub repo](https://github.com/microsoft/vscode/issues).
GitHub issues for Blazor documentation are automatically marked for triage on the [`Blazor.Docs` project (`dotnet/AspNetCore.Docs` GitHub repository)](https://github.com/dotnet/AspNetCore.Docs/projects/35). Please wait a short while for a response, especially over weekends and holidays. Usually, documentation authors respond within 24 hours on weekdays.
## Community links to Blazor resources
For a collection of links to Blazor resources maintained by the community, visit [Awesome Blazor](https://github.com/AdrienTorris/awesome-blazor).
> [!NOTE]
> Microsoft doesn't own, maintain, or support *Awesome Blazor* and most of the community products and services described and linked there.