窗体和验证

小窍门

此内容摘自电子书《面向 Azure ASP.NET Web Forms 开发人员的 Blazor》,可在 .NET 文档上获取,也可作为免费可下载的 PDF 脱机阅读。

《面向 ASP NET Web Forms 开发人员的 Blazor》电子书封面缩略图。

ASP.NET Web 窗体框架包括一组验证服务器控件,用于处理输入到窗体(RequiredFieldValidatorCompareValidatorRangeValidator等)中的用户输入的验证。 ASP.NET Web 窗体框架还支持基于数据注释([Required][StringLength][Range]等等)对模型绑定和验证模型。 可以使用基于 JavaScript 的非干扰性验证在服务器上和客户端上强制实施验证逻辑。 服务器 ValidationSummary 控件用于向用户显示验证错误的摘要。

Blazor 支持在客户端和服务器之间共享验证逻辑。 ASP.NET 提供了许多常见服务器验证的预建 JavaScript 实现。 在许多情况下,开发人员仍必须编写 JavaScript 才能完全实现其特定于应用的验证逻辑。 可以在服务器和客户端上使用相同的模型类型、数据注释和验证逻辑。

Blazor 提供一组输入组件。 输入组件处理将字段数据绑定到模型,并在提交表单时验证用户输入。

输入组件 呈现的 HTML 元素
InputCheckbox <input type="checkbox">
InputDate <input type="date">
InputNumber <input type="number">
InputSelect <select>
InputText <input>
InputTextArea <textarea>

EditForm 组件封装这些输入组件,并通过 EditContext 协调验证过程。 在创建EditForm时,您可以使用Model参数指定要绑定的模型实例。 验证通常使用数据注释完成,并且它是可扩展的。 若要启用基于数据注释的验证,请将DataAnnotationsValidator组件添加为EditForm的子级。 EditForm组件提供了一个便捷事件,用于处理有效(OnValidSubmit)和无效(OnInvalidSubmit)提交。 还有一个更通用 OnSubmit 的事件,允许你自行触发和处理验证。

若要显示验证错误摘要,请使用 ValidationSummary 组件。 若要显示特定输入字段的验证消息,请使用 ValidationMessage 组件,为 For 指向相应模型成员的参数指定 lambda 表达式。

以下模型类型使用数据注释定义多个验证规则:

using System;
using System.ComponentModel.DataAnnotations;

public class Starship
{
    [Required]
    [StringLength(16,
        ErrorMessage = "Identifier too long (16 character limit).")]
    public string Identifier { get; set; }

    public string Description { get; set; }

    [Required]
    public string Classification { get; set; }

    [Range(1, 100000,
        ErrorMessage = "Accommodation invalid (1-100000).")]
    public int MaximumAccommodation { get; set; }

    [Required]
    [Range(typeof(bool), "true", "true",
        ErrorMessage = "This form disallows unapproved ships.")]
    public bool IsValidatedDesign { get; set; }

    [Required]
    public DateTime ProductionDate { get; set; }
}

以下组件演示如何在Blazor中基于Starship模型类型构建表单。

<h1>New Ship Entry Form</h1>

<EditForm Model="@starship" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p>
        <label for="identifier">Identifier: </label>
        <InputText id="identifier" @bind-Value="starship.Identifier" />
        <ValidationMessage For="() => starship.Identifier" />
    </p>
    <p>
        <label for="description">Description (optional): </label>
        <InputTextArea id="description" @bind-Value="starship.Description" />
    </p>
    <p>
        <label for="classification">Primary Classification: </label>
        <InputSelect id="classification" @bind-Value="starship.Classification">
            <option value="">Select classification ...</option>
            <option value="Exploration">Exploration</option>
            <option value="Diplomacy">Diplomacy</option>
            <option value="Defense">Defense</option>
        </InputSelect>
        <ValidationMessage For="() => starship.Classification" />
    </p>
    <p>
        <label for="accommodation">Maximum Accommodation: </label>
        <InputNumber id="accommodation" @bind-Value="starship.MaximumAccommodation" />
        <ValidationMessage For="() => starship.MaximumAccommodation" />
    </p>
    <p>
        <label for="valid">Engineering Approval: </label>
        <InputCheckbox id="valid" @bind-Value="starship.IsValidatedDesign" />
        <ValidationMessage For="() => starship.IsValidatedDesign" />
    </p>
    <p>
        <label for="productionDate">Production Date: </label>
        <InputDate id="productionDate" @bind-Value="starship.ProductionDate" />
        <ValidationMessage For="() => starship.ProductionDate" />
    </p>

    <button type="submit">Submit</button>
</EditForm>

@code {
    private Starship starship = new Starship();

    private void HandleValidSubmit()
    {
        // Save the data
    }
}

表单提交后,模型绑定的数据尚未保存到任何数据存储,例如数据库。 在 Blazor WebAssembly 应用中,必须将数据发送到服务器。 例如,使用 HTTP POST 请求。 Blazor在服务器应用中,数据已在服务器上,但必须持久保存。 在 Blazor 应用中处理数据访问是 “处理数据 ”部分的主题。

其他资源

有关应用中的Blazor的详细信息,请参阅Blazor文档。