728x90
728x170

enum 값을 콤보로 표시하는 방법입니다.

Model 에 enum 필드를 정의합니다. (Gender)

ExampleModel.cs

using System.ComponentModel.DataAnnotations;

using Blazor.AppTest.Data;

public class ExampleModel
{
    [Required]
    [StringLength(10, ErrorMessage = "Name is too long.")]
    public string? Name { get; set; }
    [Required]
    public int? Age { get; set; }
    public Gender Gender { get; set; } = Gender.Male;
}

화면에서 아래와 같이 사용합니다.

ValidationTest.razor

@page "/validationtest"
@using Blazor.AppTest.Data

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

    <div class="form-group row">
        <label for="Name" class="col-sm-2 col-form-label">
            Name
        </label>
        <div class="col-sm-10">
            <InputText id="Name" class="form-control" placeholder="Name"
                       @bind-Value="exampleModel.Name" />
            <ValidationMessage For="@(() => exampleModel.Name)" />
        </div>
    </div>

        <div class="form-group row">
        <label for="Age" class="col-sm-2 col-form-label">
            Age
        </label>
        <div class="col-sm-10">
            <InputNumber id="Age" class="form-control" placeholder="Age"
                         @bind-Value="exampleModel.Age" />
            <ValidationMessage For="@(() => exampleModel.Age)" />
        </div>
    </div>

     <div class="form-group row">
        <label for="gender" class="col-sm-2 col-form-label">
            Gender
        </label>
        <div class="col-sm-10">
            <InputSelect @bind-Value="exampleModel.Gender" class="form-control">
                @foreach (var gender in Enum.GetValues(typeof(Gender)))
                {
                    <option value="@gender">@gender</option>
                }
            </InputSelect>
        </div>
    </div>
    
    <br /><br />
    
    <button type="submit">Submit</button>

</EditForm>

@code {
    private ExampleModel exampleModel = new();

    private bool isValidationCheck = true;

    protected override void OnInitialized()
    {
        base.OnInitialized();
    }

    private void HandleValidSubmit()
    {
        Console.WriteLine("HandleValidSubmit");
    }
}

결과

 [Source]
https://github.com/kei-soft/Blazor.AppTest/blob/master/Blazor.AppTest/Pages/ValidationTest.razor

 

GitHub - kei-soft/Blazor.AppTest

Contribute to kei-soft/Blazor.AppTest development by creating an account on GitHub.

github.com

 

728x90
그리드형
Posted by kjun
,