当前位置:网站首页>August 10, 2022: Building Web Applications for Beginners with ASP.NET Core -- Creating Web UIs with ASP.NET Core

August 10, 2022: Building Web Applications for Beginners with ASP.NET Core -- Creating Web UIs with ASP.NET Core

2022-08-10 22:35:00 DXB2021

ASP.NET Core 支持使用名为 Razor Local templating engine to create web page. This module introduces how to use Razor 和 ASP.NET Core 创建网页.

简介

通过在首选终端中运行以下命令,确保已安装 .NET 6.0:

dotnet --list-sdks

将显示类似于下面的输出:

确保列出了以 6 开头的版本.

了解使用Razor Pages的时机和原因

Razor PagesThe meaning and to provide the benefits of

Razor Pages Is a server-side programming model for the center with the page,用于使用 ASP.NET Core 构建 Web UI. Razor Pages 具有以下优点:

  • 只需使用 HTML、CSS 和 C# The combination of the definition UI 逻辑时,You can easily start building dynamic Web 应用.
  • Encouraged by the functional organization file,This can simplify the application of maintenance.
  • You can refer to HTML 文件,You can according to the used to the way in which use the tag. 你还可以使用 Razor Grammar add server side C# 代码.

Razor Pages 使用名为Razor Markup language based on server code embedded in a web page. Razor 语法是 HTML 和 C# 的组合,其中的 C# Code defines the dynamic page rendering logic. 在使用 Razor Grammar of a web page,May there are two types of content:Content of client and server code:

  • 客户端内容:Have you used in web content:HTML 标记(元素)、样式信息(如 CSS)、There may be some client-side script(如 JavaScript)和纯文本.
  • 服务器代码:使用 Razor The server code can be added to the client content. If the page contains the server code,The server will be running the code,And then send the page to the browser. By running on the server,The code can perform more complex than used alone client content task. 例如,Safe to access the database. 最重要的是,The server code to dynamically create the client content - 它可以生成 HTML Tags or other content,And together with the page may contain any static HTML Sent to the browser together. 从浏览器的角度来看,Generated on the server client content is not different with any other client content.

PageModelThe separation of concerns

Razor Pages 在 C# PageModel Class to page related data attributes and logic operation separation of concerns. Model objects are usually defined data attributes,And encapsulation associated with these data attributes of any logical or operation. 具体而言,PageModel :

  • Encapsulation is limited to the Razor Page data attribute and the logical operation.
  • To send to the page HTTP Request and used to render the page data definition page handler.

使用Razor Pages的时机

在 ASP.NET Core 应用中使用 Razor Pages 的时机:

  • 需要从 ASP.NET Core Application to generate dynamic Web UI.
  • Prefer to use page centered approach to develop Web 应用,The page markup and PageModel 会很接近.
  • Hope that centered on the page ASP.NET Core Applications use step-by-step view - 机制,In order to reduce the entire site reuse general mark the number of times.

使用 Razor Pages,Can I take a more simple way to organize ASP.NET Core 页面:

  • 在 Razor 页面 (PageModel) All the views defined in(页面)Specific logic and page properties can be stored in its own namespace and directory.
  • Related groups of the page can be stored in its own namespace and directory.

ASP.NET Core 还支持使用MVC模式 生成 Web 应用. Model defines the basic behavior of application and its components and data. 视图使用 HTML 和 Razor 语法提供 UI. The controller is receiving HTTP The request and deal with the user action class.

Preferred to generate a clear separation of the model、视图和控制器的 Web 应用时,请使用 ASP.NET Core MVC.

Razor Pages Institutions and the basis of ASP.NET Core MVC 相同. Razor Pages 和 MVC Can be in the same ASP.NET Core 应用中使用. ASP.NET Core MVC Beyond the scope of this module.

创建新的ASP.NET Core应用

创建 ASP.NET Core Web The simplest method is to use the application .NET CLI. 安装 .NET SDK 时,System will be pre-installed CLI.

创建Web应用项目

为了设置 .NET Project to Web Application work together,你将使用 Visual Studio Code. Visual Studio Code 包含一个集成终端,It easy to create a new project.

在 Visual Studio Code 中,选择“文件”>“打开文件夹”.

在所选位置创建名为 RazorPagesPizza 的新文件夹,然后单击“选择文件夹”. If you display a message,询问“If you trust the author of the files in this folder?”请选择 Yes 按钮.

从主菜单中选择“视图”>“终端”,以便从 Visual Studio Code 中打开集成终端.

在终端窗口中,输入以下命令.

dotnet new webapp -f net6.0

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows

PS C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\ASP.NET\RazorPagesPizza> dotnet new webapp -f net6.0

欢迎使用 .NET 6.0!
---------------------
SDK 版本: 6.0.303

遥测
---------
.NET 工具会收集用法数据,帮助我们改善你的体验.它由 Microsoft 收集并与社区共享.你可通过使用喜欢的 shell 将 DOTNET_CLI_TELEMETRY_OPTOUT 环境变量设置为 "1" 或 "true" 来选择退出遥测.

阅读有关 .NET CLI 工具遥测的更多信息: https://aka.ms/dotnet-cli-telemetry

----------------
已安装 ASP.NET Core HTTPS 开发证书.
若要信任该证书,请运行 "dotnet dev-certs https --trust" (仅限 Windows 和 macOS).

正在处理创建后操作...
在 C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\ASP.NET\RazorPagesPizza\RazorPagesPizza.csproj 上运行 “dotnet restore”...
  正在确定要还原的项目…
  已还原 C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\ASP.NET\RazorPagesPizza\RazorPagesPizza.csproj (用时 104 ms).
已成功还原.


PS C:\Users\a-xiaobodou\OneDrive - Microsoft\Projects\ASP.NET\RazorPagesPizza>

This command to create a basic Web Application project file,以及名为 RazorPagesPizza.csproj 的 C# 项目文件.

Visual Studio Code 可能会提示你添加资产以调试项目. 单击对话框上的“Yes”.

此命令使用 ASP.NET Core 项目模板来创建基于 C# 的 Web Application program frame. 此命令会创建 RazorPagesPizza 目录,其中包含在 .NET 上运行的 ASP.NET Core 项目. 项目名称与 RazorPagesPizza 目录名称匹配.

你现在应可以访问以下文件.

-| obj
-| Pages
   - | Shared
   - | _ViewImports.cshtml
   - | _ViewStart.cshtml
   - | Error.cshtml
   - | Error.cshtml.cs
   - | Index.cshtml
   - | Index.cshtml.cs
   - | Privacy.cshtml
   - | Privacy.cshtml.cs
-| Properties
-| wwwroot
-| appsettings.Development.json
-| appsettings.json
-| Program.cs
-| RazorPagesPizza.csproj

运行Razor PagesProject and browse themUI

编译并运行该项目

在命令行界面中运行以下 .NET Core CLI 命令:

dotnet run

上述命令:

  • 在当前目录中找到项目文件.
  • 检索并安装此项目所需的任何项目依赖项.
  • 编译项目代码.
  • 使用 ASP.NET Core 的 Kestrel Web 服务器将 Web 应用托管在 HHTP 和 HTTPS 终结点中.

创建项目时,将为 HTTP 选择 5000-5300 端口,为 HTTPS 选择 7000-7300 端口. 与往常一样,通过编辑项目的 launchSettings.json 文件,可以轻松更改开发过程中使用的端口. This module used to https 开头的安全 localhost URL.

Now listening on: https://localhost:7192
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5211
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
  Content root path: /home/<user>/aspnet-learn/src/RazorPagesPizza

If in your own computer to run this application,You can point your browser to the output shown in the HTTPS 链接(In one case for https://localhost:7192)以查看生成的页面.

浏览应用

  1. Please note that the terminal output shown in the HTTP URL,例如 https://localhost:7192.

  2. 通过浏览到 HTTPS URL,Open in a browser application.

  3. Click on the links in the navigation at the top of the page bar,导航到“隐私”页. 请注意,URL 以“Privacy”结尾. 按照约定,Razor Pages Applying the page mapped to routing Pages Files in the directory structure.

  4. 通过按 Ctrl+C 键组合(在 Mac 上为 Command+C),停止应用程序.

Has been verified can compile successfully、Run and deploy the project. Let's modify it,So that users can display and update the list of pizza.

浏览Razor Pages项目

了解项目

RazorPagesPizza Project directory of the current in the Visual Studio Code 编辑器中打开. The following table lists the project files and directories need to pay attention to. 在 Visual Studio Code In the editor window check every directory.

名称说明
Pages/包含 Razor Pages 和支持文件. 每个 Razor Pages are a pair of file:
* 一个 .cshtml 文件,其中包含使用 Razor Grammar and with C# Code mark.
* .cshtml.cs   PageModel 类文件,Definable page handler methods and data used to render the page.
wwwroot/File containing static assets,例如 HTML、JavaScript 和 CSS.
RazorPagesPizza.csproj包含项目的配置元数据,例如依赖项.
Program.csAct as application hosting the entry point and configure the application behavior,For example, routing between page.

RazorPage file and its matchingPageModel类文件

按照约定,Page 目录是在 ASP.NET Core Applications store and organize all the Razor Pages 的位置.

Razor 页面具有 .cshtml 文件扩展名. 按照约定,其关联的 PageModel C# Class files using the same name,But for .cs. 例如,Razor 页面 Index.cshtml 的关联 PageModel 类文件是 Index.cshtml.cs.

Define data model object attribute,Relating to these data attributes and encapsulation of the Boolean or operator. PageModel In essence the same,But more specifically the model encapsulate data attributes and logical operation,The scope is limited to the Razor 页面. PageModel 类:

  • 支持从 Razor Page shows the contents of the separation of the logic.
  • For requests sent to the page and used to render the page data definition page handler.

Page handler is as HTTP The result of the request execution method. 例如,Razor 页面的 PageModel 类中的 OnGet Methods for HTTP GET Request automatically perform.

Pages/Shared目录

按照约定,在多个 Razor Pages Sharing division tag element is located in the Pages/Shared 目录中. RazorPagesPizza The branch applications use two Shared view,The view is in creating a new ASP.NET Core Web When application project contains:

  • _Layout.cshtml:In multiple pages provide public layout elements.
  • _ValidationScriptsPartial.cshtml:提供验证功能,If client form input validation and cross-site anti-counterfeiting validation. This division can be used to view all the pages in the project.

The layout and division view file

  • 布局:在 ASP.NET Core 中,Layout refers to .cshtml 文件,For application of the top view definition template. Application does not need to layout. Applications can define multiple layout,The different view to specify different layout. 大多数 Web 应用都有一个通用布局,Can provide a consistent user experience. Layout usually include common UI 元素,Such as application header、Navigation menu or element and the footer. Many pages in the application also often use common HTML 结构,Such as the scripts and stylesheets. All of these elements can be defined in the layout file sharing,Any view can then be used by applications reference the file. Layout can reduce duplicate code in the view.

  • 分布视图:Division of a view is Razor 标记文件 (.cshtml),In another tag files present the output of the rendered in HTML 输出. Partial view large tag files can be broken up into smaller components. Can also be a reduction of the content of common tag tag files. Division of the view is used to maintain public layout elements. Public layout element is in _Layout.cshtml 文件中指定的.

PagesThe directory structure and routing requests

默认情况下,Razor Pages 在 Pages Directory using the directory structure as the terms of the routing request. 例如,位于 Pages Directory in the root directory index page is the application site default page. 在 RazorPagesPizza 项目的 Pages/Products 目录中,可以找到一系列 Razor 页面,其中包括 Index.cshtml 页面. 例如,路由到 /Product/ The request will be directed,To use the actual in such as Products/Index.cshtml 的默认 Index.cshtml 页面. 为方便起见,该项目的 Razor 页面 (.cshtml) 和随附的 PageModel 类 (.cshtml.cs) Has been classified as to Pages/Products. All delivery routing parameter values can be accessed through attributes in. ASP.NET Core Provide a powerful routing functions.

The table below provides the module to complete the project will use routing.

URL映射到此 Razor 页面
www.domain.comPages/Index.cshtml
www.domain.com/indexPages/Index.cshtml
www.domain.com/productsPages/Products/Index.cshtml
www.domain.com/products/createPages/Products/Create.cshtml

Add a form page list of pizza

使用 Razor Pages Isolated from the content of the page rendering the logic,在 RazorPagesPizza Project to create a form.

创建页面

RazorPagesPizza Project directory of the current in the Visual Studio Code 中打开. 在命令行界面中运行以下 .NET CLI 命令:

dotnet new page --name Pizza --namespace RazorPagesPizza.Pages --output Pages

上述命令:

  • 将在 RazorPagesPizza.Pages Namespaces create the following files:
    • Pizza.cshtml—Razor 页面
    • Pizza.cshtml.cs—随附的 PageModel 类
  • The two files are stored in the project Pages 目录中.

请注意,使用 CLI To create the file and there's nothing magical about. Can also manually create the file;CLI Command just do this shortcut.

了解Razor页面的结构

打开新的 Pages/Pizza.cshtml Razor 页面. Check the file tag:

@page
 @model RazorPagesPizza.Pages.PizzaModel
 @{
 }

上面的 Razor Page contains has reserved Razor 关键字:

  • @page Instructions page into Razor 页面. It says the page can handle HTTP 请求. @page 指令必须是 Razor The first instruction on the page.
  • @model 指令指定可用于 Razor Page model type. 在此示例中,该类型是 PageModel Derived from the name of the class,And its namespace prefix. 如之前所述,该类是在 Pages/Pizza.cshtml.cs 中定义的.

呈现HTML并转换为C#

The following tag is @ 符号后跟 C# 代码的一个示例. 此代码将 ViewData 集合的 Title 键值设置为 Create. Razor 语法使用 @ 符号从 HTML 转换为 C#. 如果 @ 符号后跟 Razor 保留关键字,It will convert Razor 特定的标记;否则,它将转换为 C#. Razor 计算 C# Expression and render it in HTML 输出中.

@{
    ViewData["Title"] = "Pizza";
}

Razor 页面支持 Razor 语法,This grammar will combine HTML 和 C#. C# Dynamic rendering logic code defined on the server page. 默认的 Razor 语言为 HTML. 从 Razor 标记呈现 HTML 与从 HTML 文件呈现 HTML 没有什么不同. Server rendering .cshtml Razor In the page file HTML Mark and no change. 在 Razor Pages 中,You can use as usual HTML. 与此同时,When you are learning to use a powerful, time-saving Razor 功能后,Can use these functions.

添加Pizza和PizzaService类

Before starting the implementation management form of pizza,Need to add a data store for performing operations.

We need to use a model class to represent the inventory of pizza. Model contains is used to represent properties characteristic of pizza. 模型用于在 Web Transfer data in the application,Pizza and kept in a data storage options. 该数据存储是一个简单的本地内存中缓存服务. 在实际应用程序中,可以考虑将数据库(例如 SQL Server)与 Entity Framework Core 结合使用

Create a pizza model

在项目的根目录中运行以下命令,以创建 Models 文件夹:

mkdir Models

在 Visual Studio Code 中选择 Models 文件夹,并添加名为 Pizza.cs 的新文件.

Project root now contains a Models 目录,其中包含一个空的 Pizza.cs 文件. 目录名称 Models 是一种约定.

将以下代码添加到 Models/Product.cs 以定义披萨. 保存所做更改.

using System.ComponentModel.DataAnnotations;

namespace RazorPagesPizza.Models;

public class Pizza
{
    public int Id { get; set; }

    [Required]
    public string? Name { get; set; }
    public PizzaSize Size { get; set; }
    public bool IsGlutenFree { get; set; }

    [Range(0.01, 9999.99)]
    public decimal Price { get; set; }
}

public enum PizzaSize { Small, Medium, Large }

添加数据服务

在项目的根目录中运行以下命令,以创建 Services 文件夹:

mkdir Services

在 Visual Studio Code 中选择该文件夹,并添加名为 PizzaService.cs 的新文件.

将以下代码添加到 Services/PizzaService.cs,以创建内存中披萨数据服务. 保存所做更改.

using RazorPagesPizza.Models;

namespace RazorPagesPizza.Services;
public static class PizzaService
{
    static List<Pizza> Pizzas { get; }
    static int nextId = 3;
    static PizzaService()
    {
        Pizzas = new List<Pizza>
                {
                    new Pizza { Id = 1, Name = "Classic Italian", Price=20.00M, Size=PizzaSize.    Large, IsGlutenFree = false },
                    new Pizza { Id = 2, Name = "Veggie", Price=15.00M, Size=PizzaSize.Small,     IsGlutenFree = true }
                };
    }

    public static List<Pizza> GetAll() => Pizzas;

    public static Pizza? Get(int id) => Pizzas.FirstOrDefault(p => p.Id == id);

    public static void Add(Pizza pizza)
    {
        pizza.Id = nextId++;
        Pizzas.Add(pizza);
    }

    public static void Delete(int id)
    {
        var pizza = Get(id);
        if (pizza is null)
            return;

        Pizzas.Remove(pizza);
    }

    public static void Update(Pizza pizza)
    {
        var index = Pizzas.FindIndex(p => p.Id == pizza.Id);
        if (index == -1)
            return;

        Pizzas[index] = pizza;
    }
                }

This service is provided with two simple data in memory cache service pizza,默认情况下,我们的 Web Application will use these two kinds of pizza demo. 如果先停止再启动 Web 应用,内存中数据缓存将重置为 PizzaService Two of the constructor of the default pizza.

Add form tag to the“披萨”Razor页面

将 Pages/Pizza.cshtml Replace with the following the content of the tag. 保存所做更改.

@page
@using RazorPagesPizza.Models
@model RazorPagesPizza.Pages.PizzaModel
@{
    ViewData["Title"] = "Pizza List";
}

<h1>Pizza List </h1>
<form method="post" class="card p-3">
    <div class="row">
        <div asp-validation-summary="All"></div>
    </div>
    <div class="form-group mb-0 align-middle">
        <label asp-for="NewPizza.Name">Name</label>
        <input type="text" asp-for="NewPizza.Name" class="mr-5">
        <label asp-for="NewPizza.Size">Size</label>
        <select asp-for="NewPizza.Size" asp-items="Html.GetEnumSelectList<PizzaSize>()" class="mr-5"></select>
        <label asp-for="NewPizza.Price"></label>
        <input asp-for="NewPizza.Price" class="mr-5" />
        <label asp-for="NewPizza.IsGlutenFree">Gluten Free</label>
        <input type="checkbox" asp-for="NewPizza.IsGlutenFree" class="mr-5">
        <button class="btn btn-primary">Add</button>
    </div>
</form>
<table class="table mt-5">
    <thead>
        <tr>
            <th scope="col">Name</th>
            <th scope="col">Price</th>
            <th scope="col">Size</th>
            <th scope="col">Gluten Free</th>
            <th scope="col">Delete</th>
        </tr>
    </thead>
    @foreach (var pizza in Model.pizzas)
    {
        <tr>
            <td>@pizza.Name</td>
            <td>@($"{pizza.Price:C}")</td>
            <td>@pizza.Size</td>
            <td>@Model.GlutenFreeText(pizza)</td>
            <td>
                <form method="post" asp-page-handler="Delete" asp-route-id="@pizza.Id">
                    <button class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
    }
</table>

@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

“披萨”Razor 页面使用 HTML 和 Razor To support products to create the form. The form to accept to create product“名称”和“价格”值. With a relatively small number of tag,Dynamic capabilities have passed Razor 标记帮助程序提供. Client form input validation by including Pages/Shared/_ValidationScriptsPartial.cshtml Division of the view to enable. The division view will be injected into the content of the page layout Scripts 部分.

了解Razor标记帮助程序

在 HTML 和 C# A context switch between will reduce the efficiency,Tags help program solves this problem. ASP.NET Core Built-in most tags help program can be extended standard HTML 元素. Tags help program for HTML Element provides additional server features,The element is more reliable.

This page has four tags help program:

  • 部分
  • Label
  • 输入
  • Verify the message

分部标记帮助程序

The following tag using division markers help asynchronous rendering division view:

<partial name="_ValidationScriptsPartial" />

Part marking help program name Attributes accept excluding file extension division view name. View find to look for in the project process division view.

This tag syntax helper alternative the following HTML Help program syntax:

@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

Tags help program

The following tag label tag is used to help the program:

<label asp-for="NewPizza.Name" class="control-label"></label>

Tags help program would extend the standard HTML <label> 元素. Like many markers help program,它使用 asp-for 特性. This feature is to accept the specified PageModel 属性. PageModelName 属性的值将作为 HTML <label> The contents of the element. asp-for Feature is limited to the scope of the Razor 页面的 PageModel,因此不使用 @ 符号. As required here,标记是动态的,But will keep it simple and easy to add to the tag.

The input tag helper

The following tag using input tags to help. It extended standard HTML <input> 元素. 它还使用 asp-for 特性来指定 PageModel 属性.

<input asp-for="NewPizza.Name" class="form-control" />

The input tag helper:

  • Similar to label tag help program,评估 NewPizza.Name 属性.
  • Based on the attribute to add id 和 name HTML 属性.
  • Properly set input type. 例如,If the specified attribute types as bool,则 checkbox Input type will be used to generate the HTML. 本例中,NewPizza.Name 属性类型为 stringNewPizza.Name Attribute is set up by the model of data annotation features,We will discuss these features in this module later.
  • Based on through PageModel Annotation feature USES for the data of the model jQuery 提供客户端验证.
  • 如果客户端验证成功,则提示 Razor Server-side validation engine provides more reliable. This module will gradually later demo“披萨”Razor 页面的 HTTP POST 事件生命周期(Including client and server input validation).

下列 HTML 输出是从“披萨”Page of the input tags help program generation:

<input name="NewPizza.Name" class="form-control" id="NewPizza_Name" type="text" value="" data-val-required="The Name field is required." data-val="true">

Verify the tags helpers

The following tag used to verify the tag helper. It a single attribute on the display model validation message.

<div asp-validation-summary="All"></div>

The input tags will help program HTML5 data- Features added to the input element. These particular based on C# Model class attributes in the. When the client authentication response type,Will perform validation on the server(这更安全).

Verify the tags helpers will present the following HTML:

<input name="NewPizza.Price" class="form-control" id="NewPizza_Price" type="text" value="" data-val-required="The Price field is required." data-val="true" data-val-range-min="0.01" data-val-range-max="9999.99" data-val-range="The field Price must be between 0.01 and 9999.99." data-val-number="The field Price must be a number.">

typedata-val-range-mindata-val-range-max And the error response is by the model Product.Price Attribute data annotations dynamically setting.

“产品创建”Razor 页面已创建. In order to handle the form interaction,需要修改 PageModel Class to handle the form HTTP POST 请求. 接下来,让我们来探讨 PageModel 交互.

使用PageModelHandler methods dealing with interaction

了解Razor Pages PageModel类的结构

新的 PageModel The class file contains the following C# 代码:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPagesPizza.Pages
{
    public class PizzaModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}

Razor 页面的 PageModel The class file for sending to the page HTTP The request handler defined any page,And data definition used to render the page. PageModel 从 Razor Page separate these concerns,The application of modularization level higher,更易于维护. 按照约定,PageModel 类命名为 [PageName]Model 并与 Razor Page in the same namespace. PizzaModel 类位于 RazorPagesPizza.Pages 的命名空间中.

PizzaModel Class USES empty OnGet Page handler HTTP GET 请求. 可以为任何 HTTP Predicate add handlers. The most common handler is:

  • OnGet,Used to initialize the page required state.
  • OnPost,Used to handle the form submission.

“披萨”Page contains a form,因此需要一个 HTTP POST 页面处理程序.

PageModel中的HTTP POST页面处理程序

OnPostAsync Page handler applications need to perform the following tasks:

  • 验证发送到 PageModel The user submits the data is valid.
  • 如果尝试的 PageModel 更改无效,Is displayed to the user again“披萨”页面. Displays a clear input request message.
  • 如果 PageModel 更新有效,Will transfer data changes to called PizzaService 的服务. PizzaService Keep the processing of the data problem.

绑定模型

PizzaModel 类需要 Pizza Access model. It will validate and pass“披萨”窗体中的 Pizza 条目. The operation by using the following code in [BindProperty] 特性来实现:

[BindProperty]
public Pizza NewPizza { get; set; }

Bound to the properties can reduce the amount of code you must write. The binding by using the same attributes to render the fields(例如在 <input asp-for="Pizza.Name"> 中),从而减少代码.

使用ASP.NET CoreBuilt-in server-side model validation data notes

创建 ASP.NET Core Web Application provides the model binding and validation. Both prior to the start page handler happen automatically. 因此 OnPostAsync The results of the handler simply determine.

if (!ModelState.IsValid)
{
    return Page();
}

在上述代码中,ModelState Said model binding and validation errors in the. 如果 ModelState 无效,Is displayed to the user again“披萨”页面. A unit has been introduce“披萨”Razor 页面如何使用 ASP.NET Core Built-in client form input validation to users provide input validation feedback quickly.

如果 ModelState 有效,OnPostAsync Page handler will be called PizzaService 的实例. PizzaService Responsible for store information - Use the data stored in the memory.

Use data annotations define validation rules for pizza model

This project USES a center model file Pizza.cs 进行 Pizza Model validation and operation. It is available for UI Involved in all Razor 页面 PageModels 用于执行 Pizza CRUD 操作,And can be used to verify from Web API 接收的“披萨”数据. 按照约定,它存储在 Models 目录中. Pizza Model namespace is RazorPagesPizza.Models.

新 PizzaModel Class through the following using Instructions for the RazorPagesPizza.Models Namespace is defined in any model type(包括 Pizza 模型)的访问权限:

using RazorPagesPizza.Models;

检查 Pizza 模型类:

using System.ComponentModel.DataAnnotations;

namespace RazorPagesPizza.Models
{
    public class Pizza
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }
        public PizzaSize Size { get; set; }
        public bool IsGlutenFree { get; set; }

        [Range(0.01, 9999.99)]
        public decimal Price { get; set; }
    }

    public enum PizzaSize { Small, Medium, Large }
}

The characteristics of data annotation is used to specify the required behavior,These behaviors will be applicable to its model properties to enforce.

Pizza 类使用:

  • [Required] Features indicate attributes must have a value.
  • [Range] 特性,Used to limit values for a specific range.

If you want to enforce more validation rules,You can easily in one place(Pizza 模型)Modify properties,Don't need to modify the project in any PageModel 类文件. This is a significant advantage!

System.ComponentModel.DataAnnotations Provides a comprehensive set of data in the annotation feature. 

As the data transfer object model of pizza

Pizza Model is the same as the data transfer object (DTO) . DTO 是一个对象,Definition will send data through the network,数据发往 Web API. In the more advanced version of the application,RazorPagesPizza 项目的 PizzaService 类将使用 Pizza 模型作为 DTO,该 DTO 定义了有效的“披萨”数据,在 Web API Or backup database can send and receive the data.

接下来,将更新与 PizzaService 类的交互 PizzaModel To list the existing pizza and create the new pizza.

Deal with pizza form submit

将为“披萨”Razor Page form add HTTP POST 页面处理程序. The final will gradually complete Pizza Model and used to drive the client-side and server-side validation data notes.

了解Razor Pages PageModel类的结构

打开 Pages/Pizza.cshtml.cs PageModel 类文件. 你可能还记得,在创建名为“披萨”的新 Razor 页面时,生成了名为 Pizza.cshtml.cs 的 PageModel 类文件. 检查内容. 其中包含以下 C# 代码:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPagesPizza.Pages
{
    public class PizzaModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}

更新HTTP GetPage handler to display the list of pizza

现在,PizzaModel Class USES empty OnGet Page handler HTTP GET 请求. Let's update it to show PizzaService The list of pizza.

更新OnGetd页面处理程序

更新 OnGet 方法,如下所示:

public void OnGet()
{
    pizzas = PizzaService.GetAll();
}

将一个名为 pizzas 的 List<Pizza> 变量添加到 PizzaModel 类中:

public List<Pizza> pizzas = new();

调用 OnGet 方法时,它会将 PizzaService.GetAll() Methods the results of the assigned to pizzas 变量. Razor The page template will have access to this variable,This variable will be written to the list of available pizza table.

These statements refer to PizzaService 和 Pizza 类,Therefore you will need the following using 语句添加到 PizzaModel 类的顶部:

using RazorPagesPizza.Models;
using RazorPagesPizza.Services;

Utility method is used to set the list no gluten information format

IsGlutenFree 属性是一个布尔值. Can use the utility method sets the Boolean value to string format. Add the following utility method to PizzaModel 类:

public string GlutenFreeText(Pizza pizza)
{
    if (pizza.IsGlutenFree)
        return "Gluten Free";
    return "Not Gluten Free";
}

将 HTTP POST Page handler is added to the PageModel

将以下方法添加到 Pages/Pizza.cshtml.cs PageModel 类. 保存所做更改.

public IActionResult OnPost()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }
    PizzaService.Add(NewPizza);
    return RedirectToAction("Get");
}

PizzaModel Class now has an asynchronous OnPost 页面处理程序. 当用户发布“披萨”Page of the form,OnPost 将执行. You can also use optional asynchronous named suffix OnPostAsync.

OnPost Page handler applications need to perform the following tasks:

  • 验证发送到 PageModel The user submits the data is valid.
  • 如果尝试的 PageModel 更改无效,Is displayed to the user again“披萨”页面. Displays a clear input request message.
  • 如果 PageModel 更新有效,Will transfer data changes to called PizzaService 的服务. PizzaService 将处理 HTTP Request of concerns and to Web API 做出响应.

绑定模型

PizzaModel 类需要 Pizza Access model. 它将使用 [BindProperty] Verification and pass“披萨”窗体中的 Pizza 条目. 将以下代码添加到 PizzaModel 类:

[BindProperty]
public Pizza NewPizza { get; set; } = new();

为“删除”按钮添加HTTP POST处理程序

Razor Page can contain more than one form. Due to the pizza in the list“删除”Button will modify the data,因此需要 HTTP POST 而不是 HTTP GET.

将下面的 OnPostDelete 方法添加到 PizzaModel 类:

public IActionResult OnPostDelete(int id)
{
    PizzaService.Delete(id);
    return RedirectToAction("Get");
}

链接到“披萨”页面

“披萨”The page is created and implemented. Let the user to navigate to the next page.

Add position mark help program to the“索引”页

在 Pages/Shared/Layout. cshtml 中,将以下代码添加到 Home 和 Privacy Link between <nav> 部分:

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-page="/Pizza">Pizza List</a>
</li>

结果将如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RazorPagesPizza</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPagesPizza</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Pizza">Pizza List</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2021 - RazorPagesPizza - <a asp-area="" asp-page="/Privacy">Privacy</a>
        </div>
    </footer>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

保存所做更改.

The highlighted code above USES location markers help program. 标记帮助程序:

  • The user is directed to Pages/Pizzas/Create.cshtml Razor 页面,该页面与“索引”Located on the same page in the directory.
  • By adding custom HTML 属性(如 asp-page-handler)Strengthen the standard HTML 定位 (<a>) 标记.

asp-page-handler Property is used to route to asp-page 属性中定义的 Razor The specific page page handler. asp-page Attributes are used to position mark href Attribute value is set to a specific Razor 页面.

  1. 在命令行界面中运行以下 .NET CLI 命令:

    dotnet run
  2. 通过浏览到 HTTPS URL,Open in a browser application.

  3. 单击导航栏中的 Pizza List 链接,导航到新“披萨”页.

  4. Fill out the form to create a new pizza,然后单击 Add 按钮. You should see the list of new pizza in the pizza.

  5. By entering invalid pizza information(Such as pizza name or blank 10000 Or a higher price)来测试验证. You should see the display validation error message.

  6. 单击 Delete 按钮,Delete from the list of pizza. You should see the pizza disappear from the list.

     

原网站

版权声明
本文为[DXB2021]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208102149191369.html