ASP.NET Core Blazor 입력 구성 요소

참고 항목

이 문서의 최신 버전은 아닙니다. 현재 릴리스는 이 문서의 .NET 8 버전을 참조 하세요.

Important

이 정보는 상업적으로 출시되기 전에 실질적으로 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적, 또는 묵시적인 보증을 하지 않습니다.

현재 릴리스는 이 문서의 .NET 8 버전을 참조 하세요.

이 문서에서는 Blazor기본 제공 입력 구성 요소에 대해 설명합니다.

입력 구성 요소

Blazor 프레임워크는 사용자 입력을 받고 유효성을 검사하기 위한 기본 제공 입력 구성 요소를 제공합니다. 다음 표의 기본 제공 입력 구성 요소는 와 함께 EditContext지원 EditForm 됩니다.

테이블의 구성 요소는 구성 요소 태그의 양식 Razor 외부에서도 지원됩니다. 입력을 변경할 때와 양식을 제출할 때 입력의 유효성이 검사됩니다.

입력 구성 요소 렌더링 형식...
InputCheckbox <input type="checkbox">
InputDate<TValue> <input type="date">
InputFile <input type="file">
InputNumber<TValue> <input type="number">
InputRadio<TValue> <input type="radio">
InputRadioGroup<TValue> InputRadio<TValue> 자식 그룹
InputSelect<TValue> <select>
InputText <input>
InputTextArea <textarea>

InputFile 구성 요소에 대한 자세한 내용은 ASP.NET Core Blazor 파일 업로드를 참조하세요.

입력 구성 요소 렌더링 형식...
InputCheckbox <input type="checkbox">
InputDate<TValue> <input type="date">
InputNumber<TValue> <input type="number">
InputSelect<TValue> <select>
InputText <input>
InputTextArea <textarea>

참고 항목

InputRadio<TValue>InputRadioGroup<TValue> 구성 요소는 ASP.NET Core 5.0 이상에서 사용할 수 있습니다. 자세한 내용을 보려면 이 문서의 5.0 이상 버전을 선택하세요.

EditForm을 비롯한 모든 입력 구성 요소는 임의 특성을 지원합니다. 구성 요소 매개 변수와 일치하지 않는 특성은 렌더링된 HTML 요소에 추가됩니다.

입력 구성 요소는 필드가 변경될 때 유효성을 검사하기 위한 기본 동작을 제공합니다.

  • EditContext가 있는 양식의 입력 구성 요소에서 기본 유효성 검사 동작에는 기본 HTML 요소의 유효성 검사 스타일을 사용하여 필드의 상태를 유효하거나 유효하지 않은 것으로 반영하도록 필드 CSS 클래스를 업데이트하는 것이 포함됩니다.
  • EditContext가 없는 컨트롤의 경우 기본 유효성 검사는 유효하거나 유효하지 않은 상태를 반영하지만 기본 HTML 요소에 대한 유효성 검사 스타일을 제공하지 않습니다.

일부 구성 요소는 유용한 구문 분석 논리를 포함합니다. 예를 들어 InputDate<TValue>InputNumber<TValue>는 구문 분석할 수 없는 값을 유효성 검사 오류로 등록하여 구문 분석 불가능한 값을 정상적으로 처리합니다. Null 값을 허용할 수 있는 형식은 대상 필드의 Null 허용 여부도 지원합니다(예: Null 허용 정수에 대한 int?).

InputFile 구성 요소에 대한 자세한 내용은 ASP.NET Core Blazor 파일 업로드를 참조하세요.

양식 예제

이 문서의 여러 예제 및 다른 Forms 노드 아티클의 예제에서 사용되는 다음 Starship 형식은 데이터 주석을 사용하여 다양한 속성 집합을 정의합니다.

  • RequiredAttribute의 주석이 추가되기 때문에 Id가 필요합니다. Id는 하나 이상의 문자 값을 필요로 하지만 StringLengthAttribute를 사용하는 16자 미만이어야 합니다.
  • DescriptionRequiredAttribute의 주석이 추가되지 않기 때문에 선택 사항입니다.
  • Classification은 필수입니다.
  • MaximumAccommodation 속성의 기본값은 0이지만 값은 RangeAttribute당 0에서 100,000 사이여야 합니다.
  • IsValidatedDesign은 속성에 true 값이 있어야 하고 속성이 UI의 체크상자(<input type="checkbox">)에 바인딩될 때 선택된 상태와 일치해야 합니다.
  • ProductionDateDateTime이며 필수입니다.

Starship.cs:

using System.ComponentModel.DataAnnotations;

namespace BlazorSample;

public class Starship
{
    [Required]
    [StringLength(16, ErrorMessage = "Identifier too long (16 character limit).")]
    public string? Id { 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 = "Approval required.")]
    public bool IsValidatedDesign { get; set; }

    [Required]
    public DateTime ProductionDate { get; set; }
}
using System.ComponentModel.DataAnnotations;

public class Starship
{
    [Required]
    [StringLength(16, ErrorMessage = "Identifier too long (16 character limit).")]
    public string? Id { 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; }
}
using System.ComponentModel.DataAnnotations;

public class Starship
{
    [Required]
    [StringLength(16, ErrorMessage = "Identifier too long (16 character limit).")]
    public string? Id { 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; }
}
using System;
using System.ComponentModel.DataAnnotations;

public class Starship
{
    [Required]
    [StringLength(16, ErrorMessage = "Identifier too long (16 character limit).")]
    public string Id { 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; }
}
using System;
using System.ComponentModel.DataAnnotations;

public class Starship
{
    [Required]
    [StringLength(16, ErrorMessage = "Identifier too long (16 character limit).")]
    public string Id { 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; }
}

다음 양식은 다음을 사용하여 사용자 입력을 허용하고 유효성을 검사합니다.

  • 위의 Starship 모델에서 정의된 속성 및 유효성 검사입니다.
  • Blazor몇 가지 기본 제공 입력 구성 요소입니다.

선박 분류()에 대한 모델 속성이Classification 설정되면 모델과 일치하는 옵션이 검사. 예를 들어 checked="@(Model!.Classification == "Exploration")" 탐색선 분류의 경우입니다. 검사 옵션을 명시적으로 설정하는 이유는 요소 값 <select> 이 브라우저에만 있기 때문입니다. 양식이 제출된 후 서버에서 렌더링되는 경우 클라이언트의 모든 상태가 서버의 상태로 재정의되며 일반적으로 옵션을 검사 표시하지 않습니다. 모델 속성에서 검사 옵션을 설정하면 분류는 항상 모델의 상태를 반영합니다. 이렇게 하면 양식 제출 간에 분류 선택이 유지되어 서버에서 양식이 다시 렌더링됩니다. 대화형 서버 렌더링 모드가 구성 요소에 직접 적용되는 경우와 같이 양식이 서버에서 다시 렌더링되지 않는 경우 클라이언트의 요소 상태를 <select> 유지하므로 모델에서 검사 옵션의 명시적 할당이 필요하지 Blazor 않습니다.

Starship3.razor:

@page "/starship-3"
@inject ILogger<Starship3> Logger

<h1>Starfleet Starship Database</h1>

<h2>New Ship Entry Form</h2>

<EditForm Model="Model" OnValidSubmit="Submit" FormName="Starship3">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div>
        <label>
            Identifier: 
            <InputText @bind-Value="Model!.Id" />
        </label>
    </div>
    <div>
        <label>
            Description (optional): 
            <InputTextArea @bind-Value="Model!.Description" />
        </label>
    </div>
    <div>
        <label>
            Primary Classification: 
            <InputSelect @bind-Value="Model!.Classification">
                <option value="">
                    Select classification ...
                </option>
                <option checked="@(Model!.Classification == "Exploration")" 
                    value="Exploration">
                    Exploration
                </option>
                <option checked="@(Model!.Classification == "Diplomacy")" 
                    value="Diplomacy">
                    Diplomacy
                </option>
                <option checked="@(Model!.Classification == "Defense")" 
                    value="Defense">
                    Defense
                </option>
            </InputSelect>
        </label>
    </div>
    <div>
        <label>
            Maximum Accommodation: 
            <InputNumber @bind-Value="Model!.MaximumAccommodation" />
        </label>
    </div>
    <div>
        <label>
            Engineering Approval: 
            <InputCheckbox @bind-Value="Model!.IsValidatedDesign" />
        </label>
    </div>
    <div>
        <label>
            Production Date: 
            <InputDate @bind-Value="Model!.ProductionDate" />
        </label>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

@code {
    [SupplyParameterFromForm]
    private Starship? Model { get; set; }

    protected override void OnInitialized() =>
        Model ??= new() { ProductionDate = DateTime.UtcNow };

    private void Submit()
    {
        Logger.LogInformation("Id = {Id} Description = {Description} " +
            "Classification = {Classification} MaximumAccommodation = " +
            "{MaximumAccommodation} IsValidatedDesign = " +
            "{IsValidatedDesign} ProductionDate = {ProductionDate}",
            Model?.Id, Model?.Description, Model?.Classification,
            Model?.MaximumAccommodation, Model?.IsValidatedDesign,
            Model?.ProductionDate);
    }
}
@page "/starship-3"
@inject ILogger<Starship3> Logger

<h1>Starfleet Starship Database</h1>

<h2>New Ship Entry Form</h2>

<EditForm Model="Model" OnValidSubmit="Submit">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div>
        <label>
            Identifier:
            <InputText @bind-Value="Model!.Id" />
        </label>
    </div>
    <div>
        <label>
            Description (optional):
            <InputTextArea @bind-Value="Model!.Description" />
        </label>
    </div>
    <div>
        <label>
            Primary Classification:
            <InputSelect @bind-Value="Model!.Classification">
                <option value="">Select classification ...</option>
                <option value="Exploration">Exploration</option>
                <option value="Diplomacy">Diplomacy</option>
                <option value="Defense">Defense</option>
            </InputSelect>
        </label>
    </div>
    <div>
        <label>
            Maximum Accommodation:
            <InputNumber @bind-Value="Model!.MaximumAccommodation" />
        </label>
    </div>
    <div>
        <label>
            Engineering Approval:
            <InputCheckbox @bind-Value="Model!.IsValidatedDesign" />
        </label>
    </div>
    <div>
        <label>
            Production Date:
            <InputDate @bind-Value="Model!.ProductionDate" />
        </label>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

@code {
    private Starship? Model { get; set; }

    protected override void OnInitialized() =>
        Model ??= new() { ProductionDate = DateTime.UtcNow };

    private void Submit()
    {
        Logger.LogInformation("Id = {Id} Description = {Description} " +
            "Classification = {Classification} MaximumAccommodation = " +
            "{MaximumAccommodation} IsValidatedDesign = " +
            "{IsValidatedDesign} ProductionDate = {ProductionDate}", 
            Model?.Id, Model?.Description, Model?.Classification, 
            Model?.MaximumAccommodation, Model?.IsValidatedDesign, 
            Model?.ProductionDate);
    }
}

위 예제의 EditForm은 할당된 Starship 인스턴스(Model="...")를 기반으로 EditContext를 만들고 유효한 양식을 처리합니다. 다음 예제에서는 폼에 할당 EditContext 하고 양식이 제출될 때 유효성을 검사하는 방법을 보여 줍니다.

다음 예제에서

  • 이전 양식(Starship3구성 요소)의 Starfleet Starship Database 단축된 버전은 우주선의 ID에 대한 값만 허용하는 데 사용됩니다. 다른 Starship 속성은 형식의 인스턴스를 만들 때 유효한 기본값을 Starship 받습니다.
  • Submit 단추를 선택하면 Submit 메서드가 실행됩니다.
  • Submit 메서드에서 EditContext.Validate을 호출하여 양식의 유효성을 검사합니다.
  • 유효성 검사 결과에 따라 로깅이 실행됩니다.

참고 항목

Submit 다음 예제에서는 양식 값을 저장하는 경우 종종 비동기 호출(await ...)을 사용하기 때문에 비동기 메서드로 설명됩니다. 표시된 것처럼 양식이 테스트 앱에서 사용되는 경우 Submit이 단순히 동기적으로 실행됩니다. 테스트를 위해 다음 빌드 경고를 무시합니다.

이 비동기 메서드는 'await' 연산자가 부족하여 동기적으로 실행됩니다. ...

Starship4.razor:

@page "/starship-4"
@inject ILogger<Starship4> Logger

<EditForm EditContext="editContext" OnSubmit="Submit" FormName="Starship4">
    <DataAnnotationsValidator />
    <div>
        <label>
            Identifier: 
            <InputText @bind-Value="Model!.Id" />
        </label>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

@code {
    private EditContext? editContext;

    [SupplyParameterFromForm]
    private Starship? Model { get; set; }

    protected override void OnInitialized()
    {
        Model ??=
            new()
                {
                    Id = "NCC-1701",
                    Classification = "Exploration",
                    MaximumAccommodation = 150,
                    IsValidatedDesign = true,
                    ProductionDate = new DateTime(2245, 4, 11)
                };
        editContext = new(Model);
    }

    private async Task Submit()
    {
        if (editContext != null && editContext.Validate())
        {
            Logger.LogInformation("Submit called: Form is valid");

            // await ...
        }
        else
        {
            Logger.LogInformation("Submit called: Form is INVALID");
        }
    }
}
@page "/starship-4"
@inject ILogger<Starship4> Logger

<EditForm EditContext="editContext" OnSubmit="Submit">
    <DataAnnotationsValidator />
    <div>
        <label>
            Identifier:
            <InputText @bind-Value="Model!.Id" />
        </label>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

@code {
    private EditContext? editContext;

    private Starship Model { get; set; }

    protected override void OnInitialized()
    {
        Model ??= 
            new()
            {
                Id = "NCC-1701",
                Classification = "Exploration",
                MaximumAccommodation = 150,
                IsValidatedDesign = true,
                ProductionDate = new DateTime(2245, 4, 11)
            };
        editContext = new(Model);
    }

    private async Task Submit()
    {
        if (editContext != null && editContext.Validate())
        {
            Logger.LogInformation("Submit called: Form is valid");

            // await ...
        }
        else
        {
            Logger.LogInformation("Submit called: Form is INVALID");
        }
    }
}

참고 항목

할당된 후에 EditContext를 변경할 수 없습니다.

InputSelect 구성 요소가 있는 여러 옵션 선택

바인딩은 InputSelect<TValue> 구성 요소가 있는 multiple 옵션 선택을 지원합니다. @onchange 이벤트는 이벤트 인수 (ChangeEventArgs)를 통해 선택한 옵션의 배열을 제공합니다. 값은 배열 형식에 바인딩되어야 하고 배열 형식에 대한 바인딩은 InputSelect<TValue> 태그에서 multiple 특성을 선택적으로 사용 합니다.

다음 예에서는 사용자가 두 개 이상의 starship 분류를 선택해야 하지만 세 개 이하여야 합니다.

Starship5.razor:

@page "/starship-5"
@using System.ComponentModel.DataAnnotations
@inject ILogger<Starship5> Logger

<h1>Bind Multiple <code>InputSelect</code> Example</h1>

<EditForm EditContext="editContext" OnValidSubmit="Submit" FormName="Starship5">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div>
        <label>
            Select classifications (Minimum: 2, Maximum: 3):
            <InputSelect @bind-Value="Model!.SelectedClassification">
                <option value="@Classification.Exploration">Exploration</option>
                <option value="@Classification.Diplomacy">Diplomacy</option>
                <option value="@Classification.Defense">Defense</option>
                <option value="@Classification.Research">Research</option>
            </InputSelect>
        </label>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

@if (Model?.SelectedClassification?.Length > 0)
{
    <div>@string.Join(", ", Model.SelectedClassification)</div>
}

@code {
    private EditContext? editContext;

    [SupplyParameterFromForm]
    private Starship? Model { get; set; }

    protected override void OnInitialized()
    {
        Model = new();
        editContext = new(Model);
    }

    private void Submit()
    {
        Logger.LogInformation("Submit called: Processing the form");
    }

    private class Starship
    {
        [Required]
        [MinLength(2, ErrorMessage = "Select at least two classifications.")]
        [MaxLength(3, ErrorMessage = "Select no more than three classifications.")]
        public Classification[]? SelectedClassification { get; set; } =
            new[] { Classification.None };
    }

    private enum Classification { None, Exploration, Diplomacy, Defense, Research }
}
@page "/starship-5"
@using System.ComponentModel.DataAnnotations
@inject ILogger<Starship5> Logger

<h1>Bind Multiple <code>InputSelect</code> Example</h1>

<EditForm EditContext="editContext" OnValidSubmit="Submit">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div>
        <label>
            Select classifications (Minimum: 2, Maximum: 3):
            <InputSelect @bind-Value="Model!.SelectedClassification">
                <option value="@Classification.Exploration">Exploration</option>
                <option value="@Classification.Diplomacy">Diplomacy</option>
                <option value="@Classification.Defense">Defense</option>
                <option value="@Classification.Research">Research</option>
            </InputSelect>
        </label>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

@if (Model?.SelectedClassification?.Length > 0)
{
    <div>@string.Join(", ", Model.SelectedClassification)</div>
}

@code {
    private EditContext? editContext;

    private Starship? Model { get; set; }

    protected override void OnInitialized()
    {
        Model ??= new();
        editContext = new(Model);
    }

    private void Submit()
    {
        Logger.LogInformation("Submit called: Processing the form");
    }

    private class Starship
    {
        [Required]
        [MinLength(2, ErrorMessage = "Select at least two classifications.")]
        [MaxLength(3, ErrorMessage = "Select no more than three classifications.")]
        public Classification[]? SelectedClassification { get; set; } =
            new[] { Classification.None };
    }

    private enum Classification { None, Exploration, Diplomacy, Defense, Research }
}

데이터 바인딩에서 빈 문자열 및 null 값을 처리하는 방법은 C# 개체 null 값에 InputSelect 옵션 바인딩 섹션을 참조하세요.

C# 개체 null 값에 InputSelect 옵션 바인딩

데이터 바인딩에서 빈 문자열과 null 값이 처리되는 방법은 ASP.NET Core Blazor 데이터 바인딩을 참조하세요.

표시 이름 지원

몇 가지 기본 제공 구성 요소가 InputBase<TValue>.DisplayName 매개 변수를 사용하여 표시 이름을 지원합니다.

예제 양식 섹션의 Starfleet Starship Database 양식(Starship3 구성 요소)에서 새 Starship의 프로덕션 날짜는 표시 이름을 지정하지 않습니다.

<label>
    Production Date:
    <InputDate @bind-Value="Model!.ProductionDate" />
</label>

양식이 제출될 때 필드에 잘못된 날짜가 포함되는 경우 오류 메시지에 식별 이름이 표시되지 않습니다. 필드 이름 ‘ProductionDate’이 유효성 검사 요약에 표시되는 경우 ‘Production’ 및 ‘Date’ 사이에 공백이 없습니다.

ProductionDate 필드는 날짜여야 합니다.

DisplayName 속성이 ‘Production’ 및 ‘Date’ 단어 사이에 공백이 있는 식별 이름으로 설정됩니다.

<label>
    Production Date:
    <InputDate @bind-Value="Model!.ProductionDate" 
        DisplayName="Production Date" />
</label>

필드 값이 잘못된 경우 유효성 검사 요약에 식별 이름이 표시됩니다.

프로덕션 날짜 필드는 날짜여야 합니다.

오류 메시지 템플릿 지원

InputDate<TValue>InputNumber<TValue> 지원 오류 메시지 템플릿:

할당된 표시 이름을 가진 예제 양식Starfleet Starship Database 양식(Starship3 구성 요소)에서 Production Date 필드는 다음과 같은 기본 오류 메시지 템플릿을 사용하여 오류 메시지를 생성합니다.

The {0} field must be a date.

{0} 자리 표시자의 위치는 오류가 사용자에게 표시될 때 DisplayName 속성 값이 나타나는 위치입니다.

<label>
    Production Date:
    <InputDate @bind-Value="Model!.ProductionDate" 
        DisplayName="Production Date" />
</label>

프로덕션 날짜 필드는 날짜여야 합니다.

사용자 지정 템플릿을 ParsingErrorMessage에 할당하여 사용자 지정 메시지를 제공합니다.

<label>
    Production Date:
    <InputDate @bind-Value="Model!.ProductionDate" 
        DisplayName="Production Date" 
        ParsingErrorMessage="The {0} field has an incorrect date value." />
</label>

프로덕션 날짜 필드에 잘못된 날짜 값이 있습니다.

예제 양식 섹션의 Starfleet Starship Database 양식(Starship3 구성 요소)에서 기본 오류 메시지 템플릿이 사용됩니다.

The {0} field must be a date.

{0} 자리 표시자의 위치는 오류가 사용자에게 표시될 때 DisplayName 속성 값이 나타나는 위치입니다.

<label>
    Production Date:
    <InputDate @bind-Value="Model!.ProductionDate" />
</label>

ProductionDate 필드는 날짜여야 합니다.

사용자 지정 템플릿을 ParsingErrorMessage에 할당하여 사용자 지정 메시지를 제공합니다.

<label>
    Production Date:
    <InputDate @bind-Value="Model!.ProductionDate" 
        ParsingErrorMessage="The {0} field has an incorrect date value." />
</label>

ProductionDate 필드에 잘못된 날짜 값이 있습니다.