【使用Blazor构建web应用程序 .NET 6篇 上】


使用Blazor构建web应用程序 .NET 6篇 上)

使用Blazor构建web应用程序

Build web applications with Blazor微软学习文档尚未更新中文,为方便小伙伴们共同学习,博主翻译了教程,并修改了原文中个别代码错误,以下教程翻译属个人行为,如有侵权,请联系博主BlazorComponent,博主会在第一时间删除教程!
更新时间:2021-11-25 22:43:39

第一节Introduction (介绍)

QQ交流群:740905824

Blazor creates interactive web applications using .NET that allows you to share app logic on both the server and client-side, without the complexity of managing client-side JavaScript libraries.
当使用 .NET的Blazor创建交互式的网络应用程序时,Blazor允许你在服务器端和客户端之间共享应用程序逻辑,而无需使用复杂的JavaScript客户端库。

Suppose you've been hired by a pizza delivery firm to modernize their customer-facing website. You've been given web page mockups from graphic designers and you've discussed the site functionality in detail with all the stakeholders. Now, you want to begin building the site with the main pizza-browsing pages. Your team has worked with C# for many years and is less experienced with JavaScript so you want to write as much code as possible in .NET. In later modules in this learning path you'll build the checkout and authentication pages.
假设你被一家披萨外卖公司雇佣来使他们面向客户的网站与时俱进。您从平面设计师那里获得了网页模型,并与所有涉众详细讨论了网站的功能。现在,你想开始使用披萨浏览主页面来构建这个网站。你的团队已经使用C#工作了很多年,而且使用JavaScript的经验不足,因此,您希望编写尽可能多的.NET代码。在本学习路径的后续模块中,您将构建结算功能和身份验证页面。

In this module, you'll learn about Blazor components and how to use them to create a user interface that displays dynamic data.
在此模块中,你将学习Blazor组件知识,以及如何使用它们来创建一个显示动态数据的用户界面。

Learning objectives
学习目标
By the end of this session, you'll be able to:
在本课程结束时,您将能够:

  • Assemble a user interface for a web app by creating Blazor components.
    通过创建Blazor组件来组装一个Web应用程序的用户界面。
  • Access data to display in your web app.
    存取要在你的Web应用程序中显示的数据。
  • Share data in your web app between multiple Blazor components.
    在你的Web应用程序中,多个Blazor组件之间可以共享数据。
  • Bind an HTML element to a variable in a Blazor component.
    将HTML元素和Blazor组件中的变量绑定。

第二节 Create a user interface with Blazor components(使用Blazor组件创建一个用户界面)

Blazor components let you define web pages or portions of HTML that includes dynamic content using .NET code. In Blazor, you can formulate dynamic content by using C#, instead of using JavaScript.
Blazor组件允许你使用.NET代码定义包含动态内容的网页或部分HTML。在Blazor中,您可以使用C#来表达动态内容,而不是使用JavaScript。

Suppose you're working for a pizza delivery company to create a new modern website. You're starting with a welcome page that will become the landing page for most site users. You want to display special deals and popular pizzas on that page.
假设你正在为一家披萨外卖公司工作,以创建一个新的现代网站。你从一个欢迎页面开始,它将成为大多数网站用户的登陆页面。你想在那个页面上展示特价商品和受欢迎的披萨。

In this unit, you'll learn how to create components in Blazor and write code that renders dynamic content on those components.
在此单元中,你将学习如何在Blazor中创建组件,并编写在这些组件上呈现动态内容的代码。

Understand Blazor components
理解Blazor组件

Blazor is a framework that developers can use to create a rich interactive user interface (UI) by writing C# code. With Blazor, you can use the same language for all your code, both server-side and client-side, and render it for display in many different browsers, including browsers on mobile devices.
Blazor是一个框架,开发人员可以通过编写C#代码来创建一个丰富的交互式用户界面(UI)。使用Blazor,您可以对服务器端和客户端代码使用相同的语言,并将其呈现在许多不同的浏览器中,包括移动浏览器。

备注
There are two hosting models for code in Blazor apps:
Blazor应用程序的代码有两种托管模式:

  • Blazor Server. In this model, the app is executed on the web server within an ASP.NET Core app. UI updates, events, and JavaScript calls on the client side are sent through a SignalR connection between the client and the server. In this module, we'll discuss and code for this model.
    Blazor Server。在此模型中,应用程序在ASP.NET Core应用程序的web服务器上执行。客户端上的UI更新、事件和JavaScript调用将通过客户端和服务器之间的SignalR连接发送。在这个模块中,我们将讨论并编写这个模型的代码。
  • Blazor WebAssembly.In this model the Blazor app, its dependencies, and the .NET runtime are downloaded and run on the browser.
    Blazor WebAssembly. 在这个模型中,Blazor应用程序及其依赖关系和 .NET runtime将被下载并在浏览器上运行。

In Blazor, you build the UI from self-contained portions of code called components. Each component can contain a mix of HTML and C# code. Components are written using Razor syntax, in which code is marked with the @code directive and other directives can be used to access variables, bind to values, and achieve other rendering tasks. When the app is compiled, the HTML and code are compiled into a component class. Components are written as files with a .razor extension.
在Blazor中,你可以使用叫做组件的自包含代码部分来构建UI。每个组件都可以混合包含HTML和C#代码。组件使用Razor语法编写,其中代码用@code指令和其他指令访问变量、绑定值和实现呈现任务。编译应用程序时,HTML和代码被编译成一个组件类。组件被编写成扩展名为 .razor的文件。

备注
Razor syntax is used for embedding .NET code into webpages. You can use it in ASP.NET MVC applications, where files have a .cshtml extension. Razor syntax is used in Blazor to write components, but these have the .razor extension instead and there is no strict separation between controllers and views.
Razor语法用于将 .NET代码嵌入网页。你可以在ASP.NET MVC应用程序中使用,其中文件的扩展名为 .cshtml。Blazor中使用Razor语法编写组件,但这些组件扩展名使用 .razor替代,并且控制器和视图之间没有严格的分离。

Here's a simple example of a Blazor component:
下面是一个Blazor组件的简单示例:

razor

@page "/index"

<h1>Welcome to Blazing Pizza</h1>

<p>@welcomeMessage</p>

@code {
  private string welcomeMessage = "However you like your pizzas, we can deliver them blazing fast!";
}

In this example, the code sets the value of a string variable, named welcomeMessage. That variable is rendered within <p> tags in the HTML. We'll examine more complex examples later in this unit.
在本例中,代码设置一个名为welcomeMessage的字符串变量的值。该变量在HTML中的<p>标签中呈现。稍后,我们将在本单元中研究更复杂的示例。

Create Blazor components
创建Blazor组件

When you create a Blazor app, using the blazorserver template in the dotnet Command Line Interface (CLI), several components are included by default:
当你在dotnet命令行界面(CLI)中使用blazorserver模板创建Blazor应用程序时,默认情况下会包含以下几个组件:

Bash

dotnet new blazorserver -o BlazingPizzaSite -f net6.0

The default components include the Index.razor homepage and the Counter.razor demo component, both of which are placed in the Pages folder. You can either modify these views to fit your needs or delete them and replace them with new components.
默认组件包括Index.razor主页和Counter.razor演示组件,它们都放在Pages文件夹中。你可以修改这些视图以适应您的需要,也可以删除它们并用新组件替换它们。

To add a new component to an existing web app, use this command:
若要向现有的Web应用程序添加新组件,请使用以下命令:

Bash

dotnet new razorcomponent -n PizzaBrowser -o Pages
  • The-n option specifies the name of the component to add. This example adds a new file named PizzaBrowser.razor.
    -n选项指定要添加的组件的名称。此示例添加了一个名为PizzaBrowser.razor的新文件。
  • The-o option specifies the folder that will contain the new component.
    -o选项指定将包含新组件的文件夹。
  • The-f option forces the application to be built with the framework version .NET 6
    -f选项强制使用框架版本.NET 6构建应用程序。

重要
The name of a Blazor component must begin with an uppercase character.
Blazor组件的名称必须以大写字符开头。

Once you've created the component, you can open it to be edited with Visual Studio Code:
创建组件后,可以使用Visual Studio Code进行编辑:

Bash

code Pages/PizzaBrowser

Write code in a Blazor component
在Blazor组件中编写代码

When you build a user interface in Blazor, you mix static HTML and CSS markup with C# code, often in the same file. To differentiate these types of code, you use Razor syntax. Razor syntax includes directives, prefixed with the @ symbol, that delimit C# code, routing parameters, bound data, imported classes, and other features.
当你在Blazor中构建一个用户界面时,您会将静态HTML和CSS标记与C#代码混合,通常放在同一个文件中。若要区分这些类型的代码,请使用Razor语法。Razor语法包括以@符号为前缀的指令,它分隔C#代码、路由参数、绑定数据、导入的类和其他特性。

Let's consider this example component again:
让我们再次思考这个示例组件:

razor

@page "/index"

<h1>Welcome to Blazing Pizza</h1>

<p>@welcomeMessage</p>

@code {
  private string welcomeMessage = "However you like your pizzas, we can deliver them fast!";
}

You can recognize the HTML markup, with <h1> and <p> tags. This markup is the static framework of the page, into which your code will insert dynamic content. The Razor markup consists of:
您可以识别带有<h1>和<p>标签的HTML标记。此标记是页面的静态框架,代码将在其中插入动态内容。Razor标记包括:

  • The @page directive, which provides a route template to Blazor. At runtime, Blazor locates a page to render by matching this template to the URL that the user requested. In this case, it might match a URL of the form http://yourdomain.com/index.
    @page指令,它提供了一个Blazor的路由模板。在运行时,Blazor通过将此模板与用户请求的URL相匹配来定位要呈现的页面。在这种情况下,它可以匹配http://yourdomain.com/index.形式的URL。

  • The @code directive, which declares that the text in the following block is C# code. You can put as many code blocks as you need in a component. You can define component class members in these code blocks and set their values from calculation, data lookup operations, or other sources. In this case, the code defines a single component member called welcomeMessage and sets its string value.
    @code指令,它声明下面的块中文本是C#代码。你可以在组件中放置所需数量的代码块。你可以在这些代码块中定义组件类成员,并通过计算、数据查找操作或其他来源设置其值。在本例中,代码定义了一个名为welcomeMessage的单个组件成员,并设置其字符串值。

  • Member access directives. If you want to include the value of a member in your rendering logic, use the @ symbol followed by a C# expression such as the name of the member. In this case, the @welcomeMessage directive is used to render the value of the welcomeMessage member in the <p> tags.
    成员访问指令。如果要在呈现逻辑中包含成员的值,请使用 @ 符号后面跟着C#表达式,例如成员的名称。在这种情况下,@welcomeMessage指令用于在 <p> 标签中呈现welcomeMessage成员的值。
    welcome-page-rendered

第三节 Exercise - Create a user interface with Blazor components(练习-使用Blazor组件创建一个用户界面)

更新时间:2021-11-26 13:16:15

You'll be starting to create a new Blazing Pizza app for the pizza delivery company. They have provided the current CSS, imagery, and HTML from their old site to work with.
你将开始为披萨外卖公司创建一个新的Blazing Pizza应用程序。他们提供了旧站点的CSS、图像和HTML供使用。

备注
This module uses the .NET CLI (Command Line Interface) and Visual Studio Code for local development. After completing this module, you can apply the concepts using Visual Studio (Windows), Visual Studio for Mac (macOS), or continued development using Visual Studio Code (Windows, Linux, & macOS).
此模块使用 .NET CLI (命令行界面)和 Visual Studio Code 进行本地开发。完成模块后,您可以使用Visual Studio (Windows), Visual Studio for Mac (macOS),或使用Visual Studio Code (Windows, Linux, & macOS)继续本地开发。

If you haven't created a Blazor app before, follow the setup instructions for Blazor to install the correct version of .NET and check your machine is setup correctly. Stop at the Create your app step.
如果你以前没有创建过Blazor应用程序,请先停止创建应用程序的步骤,并按照Blazor的安装说明安装正确版本的 .NET和检查你的机器设置是否正确。

Create a new Blazor app
创建一个新的Blazor应用程序

This module uses the .NET 6.0 SDK. Before beginning the module, ensure that you have .NET 6.0 installed by running the following command in your preferred terminal:
此模块使用的 .NET 6.0 SDK。在开始该模块之前,通过在终端中运行以下命令,确保已安装.NET 6.0:

.NET CLI

dotnet --list-sdks

Output similar to the following appears:
此时将出现类似以下内容的输出:

控制台

3.1.100 [C:\program files\dotnet\sdk]
5.0.100 [C:\program files\dotnet\sdk]
6.0.100 [C:\program files\dotnet\sdk]

Ensure that a version starting with 6 is listed. If none is listed or the command is not found, install the most recent .NET 6.0 SDK.
确保列出了以6开头的版本。如果没有列出或没有找到该命令,请安装最新的.NET 6.0 SDK。

.NET lets you create new projects with any version of Visual Studio or terminal commands. The following exercises will show you the steps using the terminal and Visual Studio Code.
.NET允许你使用任何版本的VisualStudio或终端命令创建新项目。下面的练习将向你展示使用终端和Visual Studio Code的步骤。

1.Open Visual Studio code.
打开Visual Studio code
2.Open the integrated terminal from Visual Studio Code by selecting View, then select Terminal from the main menu.
选择或创建文件夹,然后选择“查看”菜单中的“终端”。
3.In the terminal, navigate to where you'd like the project to be created.
在终端中,导航到您希望创建项目的位置。
4.Run the dotnet terminal command:
运行dotnet终端命令:

.NET CLI

dotnet new blazorserver -o BlazingPizza --no-https true -f net6.0

This command creates a new Blazor server project, in a folder named BlazingPizza and tells the project to disable https.
此命令在一个名为BlazingPizza的文件夹中创建一个新的 Blazor server项目,并禁用该项目的https。

5.Select File, then select Open folder....
选择文件,然后选择打开文件夹…。
6.In the open dialog, navigate to the BlazingPizza folder, and select Select Folder.
在打开的对话框中,导航到BlazingPizza文件夹,然后选择“选择文件夹”。
7.Visual Studio Code will prompt you to add required assets to build and debug the project, select Yes.
Visual Studio Code将提示你添加构建和调试项目所需的支持文件,然后选择Yes。
3-install-missing-components
8.Visual Studio Code will add launch.json and tasks.json in the .vscode folder of your project.These files enable you to run and debug your Blazor app with Visual Studio Code's debugging tools.
Visual Studio Code会在项目的 .vscode 文件夹中添加 launch.jsontasks.json 两个文件。这些文件使你能够使用Visual Studio Code的调试工具来运行和调试Blazor应用程序。

Test your setup
测试设置
You can choose to use the terminal, or Visual Studio Code to run your app.
你可以选择使用终端或Visual Studio Code来运行应用程序。

1.In the terminal window, you can start the Blazor app with:
在终端窗口中,你可以通过以下方式启动Blazor应用程序:

.NET CLI

dotnet watch

This command will build and then start the app. The watch command tells dotnet to watch all your project files. Any changes you make to projects files will automatically trigger a rebuild and then restart your app.
这个命令将构建并启动应用程序。watch命令告诉dotnet监视你所有的项目文件。你对项目文件所做的任何更改都将自动触发重建,然后重新启动应用程序。

Your computers default browser should open a new page at http://localhost:5000.
你计算机默认的浏览器会在 http://localhost:5000 打开一个新页面。

2.To stop the app running, press Ctrl + C in the terminal window.
若要停止应用程序的运行,请在终端窗口中按Ctrl+C键。
You can also run and debug your project with Visual Studio Code.
你还可以使用Visual Studio Code来运行和调试项目。
①.In Visual Studio Code press F5, or in the Run menu, select Start Debugging.
在 Visual Studio Code中按F5或在“运行”菜单中选择“启动调试”。
②.The app should build, and open a new browser page.
应用程序构建,并打开一个新的浏览器页面。
③.Visual Studio Code will also switch to the Run and Debug window that allows you to restart or stop your app.
Visual Studio Code将切换到运行和调试窗口,允许你重新启动或停止应用程序。
3-visual-studio-code-debugging
④.Press Shift + F5 to stop the app running.
按Shift+F5键以停止应用程序的运行。

Download the Blazing Pizza assets and starter files
下载Blazing Pizza 资源和启动文件

You'll now clone your teams existing Blazor app project files from the GitHub repositoryhttps://github.com/MicrosoftDocs/mslearn-interact-with-data-blazor-web-apps.git
现在,您将从GitHub存储库中克隆团队现有的Blazor应用程序项目文件https://github.com/MicrosoftDocs/mslearn-interact-with-data-blazor-web-apps.git

1.Delete your BlazingPizza folder, with file explorer or in Visual Studio Code.
用文件资源管理器或Visual Studio Code删除你的BlazingPizza文件夹。
2.In the terminal, clone the current working files into a new BlazingPizza folder.
在终端中,将一个新的BlazingPizza 文件夹克隆到当前的工作文件中。

PowerShell

git clone https://github.com/MicrosoftDocs/mslearn-interact-with-data-blazor-web-apps.git BlazingPizza

3.Run the current version of the app, press F5.
运行该应用程序的当前版本,按F5键。
3-blazing-pizza-start
Make some pizzas
做一些披萨

The index.razor component is going to let customers select and configure the pizzas they'd like to order. The component responds to the root url of the app.
index.razor组件可以让客户选择和配置他们想订购的披萨。组件响应用程序的根url地址。
The team has also created classes to represent the models in the app. Review the current PizzaSpecial model.
该团队还创建了一些类来表示该应用程序中的模型。回顾当前的 PizzaSpecial(特价披萨)模型。

1.In Visual Studio Code, in the explorer expand the Model folder, then select PizzaSpecial.
展开Visual Studio Code资源管理器中的 Model文件夹,然后选择 PizzaSpecial。

C#

namespace BlazingPizza
{
    /// <summary>
    /// Represents a pre-configured template for a pizza a user can order
    /// </summary>
    public class PizzaSpecial
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public decimal BasePrice { get; set; }

        public string Description { get; set; }

        public string ImageUrl { get; set; }

        public string GetFormattedBasePrice() => BasePrice.ToString("0.00");
    }
}

2.Note that a pizza order has a Name, BasePrice, Description, and ImageUrl.
请注意,披萨订单有Name、BasePrice、Description和ImageUrl。
3.In the explorer, expand Pages and then select Index.razor.
在资源管理器中展开 Pages,然后选择Index.razor。

razor

@page "/"
<h1>Blazing Pizzas</h1>

At the moment, there is only a single H1 tag for the title. You're going to add some code to create some pizza specials.
目前,只有一个标题的H1标签。接下来你将添加一些代码来创建一些特价披萨。
4.Under the <h1> tag, add this C# code.
在 <h1> 标签的下面,添加这些C# 代码。

razor

@code {
List<PizzaSpecial> specials = new();

protected override void OnInitialized(){
  specials.AddRange(new List<PizzaSpecial>
  {
    new PizzaSpecial { Name = "The Baconatorizor", BasePrice =  11.99M, Description = "It has EVERY kind of bacon", ImageUrl="img/pizzas/bacon.jpg"},
    new PizzaSpecial { Name = "Buffalo chicken", BasePrice =  12.75M, Description = "Spicy chicken, hot sauce and bleu cheese, guaranteed to warm you up", ImageUrl="img/pizzas/meaty.jpg"},
    new PizzaSpecial { Name = "Veggie Delight", BasePrice =  11.5M, Description = "It's like salad, but on a pizza", ImageUrl="img/pizzas/salad.jpg"},
    new PizzaSpecial { Name = "Margherita", BasePrice =  9.99M, Description = "Traditional Italian pizza with tomatoes and basil", ImageUrl="img/pizzas/margherita.jpg"},
    new PizzaSpecial { Name = "Basic Cheese Pizza", BasePrice =  11.99M, Description = "It's cheesy and delicious. Why wouldn't you want one?", ImageUrl="img/pizzas/cheese.jpg"},
    new PizzaSpecial { Name = "Classic pepperoni", BasePrice =  10.5M, Description = "It's the pizza you grew up with, but Blazing hot!", ImageUrl="img/pizzas/pepperoni.jpg" }               
    });
  }
}

The @code block creates an array to hold the pizza specials. When the page is initialized, it adds six pizzas to the array.
@code块会创建一个数组来保存特价披萨。当页面被初始化时,它会向数组中添加6个披萨。

5.Press F5 or select Run and then Start Debugging.
按F5或选择运行,然后开始调试。
The app should compile and run, and you'll see nothing has changed. The code isn't being used by anything in the client-side HTML. Let's fix that.
编译和运行应用程序,你不会看到任何改变。客户端HTML中的任何东西都没有使用该代码。让我们来解决这个问题吧。
6.Press Shift + F5, or select Stop Debugging.
按Shift+F5,或选择停止调试。
7.In index.razor replace all the code in the <h1> tag with this code.
在index.razor中,用此代码替<h1>标签记中的所有代码。

razor

<div class="main">
  <h1>Blazing Pizzas</h1>
  <ul class="pizza-cards">
    @if (specials != null)
    {
      @foreach (var special in specials)
      {
        <li style="background-image: url('@special.ImageUrl')">
          <div class="pizza-info">
          <span class="title">@special.Name</span>
          @special.Description
          <span class="price">@special.GetFormattedBasePrice()</span>
          </div>
        </li>
      }
    }
  </ul>
</div>

This code combines plain HTML alongside looping and member access directives. The @foreach loop creates an <li> tag for each pizza in the specials array.
这段代码结合了纯HTML以及循环和成员访问指令。@foreach循环为specials数组中的每个pizza创建一个<li>标签。
Inside the loop, each special pizza displays its name, description, price, and image with member directives.
在循环中,每个 special pizza通过成员指令显示它的名称、描述、价格和图片。
8.Press F5 or select Run and then Start Debugging.
按F5或选择运行,然后开始调试。
3-blazing-pizzas

第四节 Access data from a Blazor component(从Blazor组件访问数据)

Engaging websites need to display dynamic content that may change all the time. Obtaining data from a dynamic source such as a database or web service is a fundamental technique in web development.
让人流连忘返的网站需要显示可以随时变化的动态内容。从动态源(如数据库或web服务)获取数据是web开发中的一项基础技术。
Suppose you're working for a pizza delivery firm on their updated customer-facing website. You have a range of web pages laid out and designed as Blazor components. Now, you want to populate those pages with information about pizzas, toppings, and orders that you want to obtain from a database.
假设你有一个工作是为一家披萨外卖公司更新他们面向客户的网站。你有一系列的网页用Blazor组件进行布局和设计。现在,你想用从数据库中获取的披萨、配料和订单等信息来填充这些页面。
In this unit, you'll learn how to access data and render it within HTML markup for display to the user.
在此单元中,你将学习如何访问数据并在HTML元素中呈现给用户。

Create a registered data service
创建注册数据服务

if you want to create a dynamic website that shows changing information to users, you must write code to get that data from somewhere. For example, suppose you have a database that stores all the pizzas your company sells. Because the pizzas are always changing, it's a bad idea to hardcode them into the website HTML. Instead, use C# code and Blazor to query the database and then format the details as HTML so that the user can pick their favorite.
如果你想创建一个动态的网站,向用户显示可变化的信息,你必须编写代码来从某个地方获取数据。例如,假设你有一个数据库来存储公司销售的所有披萨。因为披萨总是在变化,所以将它们硬编码到网站HTML中是一个坏主意。相反,使用C#代码和Blazor来查询数据库,然后将详细信息格式化为HTML,以便用户可以选择他们最喜欢的披萨。
In a Blazor Server app, you can create a registered service to represent a data source and obtain data from it.
在Blazor服务器应用程序中, 你可以创建一个注册服务来表示数据源并从中获取数据。

备注
The sources of data you can use in a Blazor app includes relational databases, NoSQL databases, web services, various Azure services, and many other systems. You can use .NET technologies such as Entity Framework, HTTP clients, ODBC, and so on to query those sources. These techniques are beyond the scope of this course. Here, you'll learn how to format and use data that you've obtain from one of these sources and technologies.
你可以在Blazor应用程序中使用的数据源包括关系数据库、NoSQL数据库、Web服务、各种Azure服务和许多其他系统。你可以使用.NET技术,如Entity Framework(实体框架)、HTTP clients(HTTP客户机)、ODBC等来查询这些数据源。这些技术超出了本课程的范围。在这里,你将学习一个格式化和使用从这个数据源获得数据的技术。
Start creating your registered service, by writing a class that defines its properties. Here's an example that you might write to represent a pizza:
通过编写一个定义其属性的类,开始创建已注册的服务。这里有一个例子,可以用来代表一个pizza:

C#

using System;
namespace BlazingPizza.Data
{
    public class Pizza
    {
        public int PizzaId { get; set; }
 
        public string Name { get; set; }
  
        public string Description { get; set; }
  
        public decimal Price { get; set; }
  
        public bool Vegetarian { get; set; }
  
        public bool Vegan { get; set; }
    }
}

The class defines the pizza's properties and datatypes. You must make sure these properties match the pizza schema in the data source. It makes sense to create this class in the Data folder of your project and use a member namespace called Data but you can choose other folders and namespaces if you prefer.
该类定义了Pizza的属性和数据类型。你必须确保这些属性与数据源中的Pizza模式相匹配。在项目的 Data 文件夹中创建此类并使用名称Data为成员命名空间是合乎常规的,但如果你愿意,你可以选择其他文件夹和命名空间。
Next, define the service:
接下来,定义服务:

C#

using System;
using System.Threading.Tasks;

namespace BlazingPizza.Data
{
    public class PizzaService
    {
        public async Task<Pizza[]> GetPizzasAsync()
        {
        // Call your data access technology here
        }
    }
}

Notice that the service uses an asynchronous call to access data and return a collection of Pizza objects. Because the data source may be remote from the server where the Blazor code is running, it's good practice to use an asynchronous call to ensure that, if the data source responds slowly, other code can continue to run as you await the response.
请注意,该服务使用异步调用来访问数据并返回Pizza对象的集合。因为数据源可能远离运行Blazor代码的服务器,所以最好使用异步调用来确保如果数据源响应缓慢,其他代码可以在您等待响应时继续运行。

You must also register the service by adding a line to the Add Services to the container section in the Program.cs file:
您还必须在Program.cs文件里将一行注册服务添加到容器中:

C#

...// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
// Register the pizzas service
builder.services.AddSingleton<PizzaService>();
...

Use a service to obtain data
使用一个服务来获取数据

The next thing to do is to use the service you've defined by calling it in a Blazor component and obtaining data. Let's suppose you have the following component code and you want to display pizzas in it:
接下来要做的是使用在Blazor组件中调用你定义的服务并获取数据。让我们假设你有以下组件代码,并且你想在其中显示pizzas:

razor

@page "/pizzas"

<h1>Choose your pizza</h>

<p>We have all these delicious recipes:</p>

Inject the service
注入服务

Before you can call the service from the component, you must use dependency injection to add the service. To do that, add the following code just after the @page directive:
在使用组件调用服务之前,必须使用依赖项注入来添加服务。为此,请在 @page 指令之后添加以下代码:

razor

@using Blazor.Data
@inject PizzaService PizzaSvc

Usually, the component and the service will be in different namespace members, so you must include the @using directive. This directive works in the same way as a using statement at the top of a C# code file. The @inject directive adds the service to the current component and initiates an instance of it. In the directive, specify the name of the service class, followed by the name you want to use for the instance of the service in this component.
通常,组件和服务将位于不同的命名空间中,因此必须包含 @using 指令。此指令的工作方式与C#代码文件顶部的using语句相同。@inject指令将服务添加到当前组件并生成一个实例。在该指令中,指定服务类的名称,然后指定用于此组件中的服务实例的名称。

Override the OnInitializedAsync method
覆盖OnInitializedAsync方法

A good place to call the service and obtain data is in the OnInitializedAsync method. This event fires when the component's initialization is complete and it has received initial parameters but before the page is rendered and displayed to the user. The event is defined on the Blazor component's base class, and you can override it in a code block like this:
OnInitializedAsync方法是调用服务并获取数据的一个好地方。在组件的初始化完成并收到初始参数后,在页面呈现给用户之前,此事件方法将被触发。该事件是在Blazor组件的基类上定义的,您可以在这样的代码块中覆盖它:

C#

protected override async Task OnInitializedAsync()
{
 \\ Call the service here 
}

Call the service to obtain data
调用服务获取数据

When you call the service, remember to use the await keyword, because the call is asynchronous:
当您调用该服务时,请记住使用await关键字,因为该调用是异步的:

C#

private Pizza[] todaysPizzas;

protected override async Task OnInitializedAsync()
{
    todaysPizzas = await PizzaSvc.GetPizzasAsync();
}

Display data to the user
向用户显示数据

Now that you have some data from the service, you should display it to the user. In our pizzas example, we expect the service to return a list of pizzas that the users can choose from. Blazor includes a rich set of directives that you can use to insert this data into the page that the user sees.
现在你拥有了来自该服务的一些数据,你应该将其呈现给用户。在pizzas示例中,我们预期该服务能返回一个用户可以从中选择的pizzas列表。Blazor包含了一组丰富的指令,你可以用这些指令将数据插入到用户所看到的页面中。

Check for data
检查数据

First, let's determine what the page displays before the pizzas are loaded. We can do this by checking whether the todaysPizzas collection is null. To run conditional rendering code in a Blazor component, use the @if directive:
首先,让我们确定在加载pizzas之前,页面会显示什么。我们可以通过检查todaysPizzas集合是否为null来做到这一点。若要在Blazor组件中运行呈现条件代码,请使用 @if 指令:

razor

@if (todaysPizzas == null){
 <p>We're finding out what pizzas are available today...</p>
}
else{
 <!-- This markup will be rendered once the pizzas are loaded(此标记将在加载pizzas后呈现) -->
}

The @if directive renders the markup in its first code block only if the C# expression returns true. You can also use an else if code block to run other tests and render markup if they are true. Finally, you can specify an else code block to render code if none of the previous conditions returned true. By checking for null in the @if code block, you ensure that Blazor won't try to display pizza details before data has been obtained from the service.
只有当C#表达式返回 true时,@if指令才会在其第一个代码块中呈现<p>标签标记的内容。你还可以使用else if代码块运行其他测试,如果标记为true,则呈现标记。最后,如果前面的条件都没有返回true,则可以指定一个 else 代码块来呈现代码。通过在 @if代码块中检查 null,可以确保Blazor不会在从服务中获取数据之前尝试显示披萨的详细信息。

备注
Blazor also includes the @switch directive for rendering markup based on a test that may return multiple values. This works in a similar way to the C# switch statement.
Blazor还包括 @switch 指令,用于可能返回多个值的呈现标记测试上。它的工作方式类似于C#switch语句。

Render a collection of objects
呈现一个对象的集合

If Blazor executes the else statement in the above code, then you know that some pizzas have been obtained from the service. Your next task is to display these to the user. Let's construct a simple HTML table to display them.
如果Blazor在上述代码中执行了else语句,那么你就知道已经从该服务中获得了一些pizzas。你的下一个任务是将这些内容展示给用户。让我们构造一个简单的HTML表来显示它们。

razor

<table>
   <thead>
    <tr>
     <th>Pizza Name</th>
     <th>Description</th>
     <th>Vegetarian?</th>
     <th>Vegan?</th>
     <th>Price</th>
    </tr>
   </thead>
   <tbody>
    @foreach (var pizza in todaysPizzas)
    {
     <tr>
      <td>@pizza.Name</td>
      <td>@pizza.Description</td>
      <td>@pizza.Vegetarian</td>
      <td>@pizza.Vegan</td>
      <td>@pizza.Price</td>
     </tr>
    }
   </tbody>
</table>

4-simple-pizza-list
Of course, you probably want a richer display of pizzas than the plain table displayed in this example and you might want to format the price and other values. Work with your graphic designers to develop a more engaging user interface, for example with pictures of each pizza.
当然,你可能希望获得比本示例中显示的纯文本表格更丰富的pizzas显示,并且你可能希望格式化价格和其他值。与你的平面设计师一起开发一个更吸引人的用户界面,例如使用每个披萨的图片。

备注
Blazor includes other looping directives, including @for, @while, and @do while. These directives return repeated blocks of markup and work in a similar way to the equivalent C# for, while, and do...while loops.
Blazor包括其他循环指令,包括 @for, @while@do while。这些指令返回重复的标记块,并以类似于C#的for, while, 和 do…while 循环方式工作。

Check your knowledge
检查你的知识

1. In which Blazor event handler is a good place to fetch data?
哪个Blazor事件处理程序是一个获取数据的好地方?
A.PageLoad

B.OnInitializedAsync

C.OnAfterRenderAsync

2. Which Blazor directive should you use to work with a data access service on a Blazor page?
您应该使用哪个Blazor指令来处理Blazor页面上的数据访问服务?
A.@inject

B.@page

C.@using

答案:1.(B) 2.(A)

第五节 Exercise - Access data from a Blazor component (练习-从Blazor组件访问数据)

使用Blazor构建web应用程序 .NET 6篇 中
下一篇 https://blog.csdn.net/BlazorComponent/article/details/121566878

  • 7
    点赞
  • 6
    收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:1024 设计师:我叫白小胖 返回首页
评论 2

打赏作者

BlazorComponent

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值