前言

今天介紹輸入類型的表單,熟悉各種內建的元件可以讓在做表單時不用自己造輪子,使用現成的元件,如果遇到既有的元件無法解決需求那我們再來自己製作元件

InputCheckbox

單選的勾選,用來處理 bool 值的輸入元件,經過轉譯後為 <input type="checkbox">

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@page "/InputSample"
<EditForm Model="@inputSampleModel">
    <label>勾選</label>
    <InputCheckbox @bind-Value="inputSampleModel.IsCheck"></InputCheckbox>
</EditForm>

@code {
    private InputSampleModel inputSampleModel = new();
    class InputSampleModel
    {
        public bool IsCheck{ get; set; }
    }
}

勾選的時候 inputSampleModel.IsCheck 就會變成 true 反之亦然

InputDate

日期元件,支援 DataTimeDateTimeOffset 兩個型別,經過轉譯後為 <input type="date">

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@page "/InputSample"
<EditForm Model="@inputSampleModel">
    <label>日期元件(DateTime)</label>
    <InputDate @bind-Value="inputSampleModel.DateTime"></InputDate>
    <br>
    <label>日期元件(DateTimeOffset)</label>
    <InputDate @bind-Value="inputSampleModel.DateTimeOffset"></InputDate>
</EditForm>

@code {
    private InputSampleModel inputSampleModel = new();
    class InputSampleModel
    {
        public DateTime DateTime{ get; set; }
        public DateTimeOffset DateTimeOffset { get; set; }
    }
}

InputFile

檔案上傳元件經過轉譯後為 <input type="file">,可以到第11篇去看一下詳細的做法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
@page "/InputSample"
<EditForm>
    <label>檔案上傳</label>
    <InputFile OnChange="@LoadFiles" multiple ></InputFile>
</EditForm>

@code {
    private InputSampleModel inputSampleModel = new();
    class InputSampleModel
    {
        public List<IBrowserFile> loadedFiles { get; set; }
    }

    private async Task LoadFiles(InputFileChangeEventArgs e)
    {

        foreach (var file in e.GetMultipleFiles())
        {
            inputSampleModel.loadedFiles.Add(file);
        }
    }
}

InputNumber

用來處理數字的輸入,如果輸入的值不可以解析就會被便認為錯誤,經過轉譯後為 <input type="number">

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@page "/InputSample"
<EditForm Model="@inputSampleModel">
    <label>數字</label>
    <InputNumber @bind-Value="inputSampleModel.Value"></InputNumber>
</EditForm>

@code {
    private InputSampleModel inputSampleModel = new();
    class InputSampleModel
    {
        public int Value{ get; set; }
    }
}

InputSelect

下拉選單元件,經過轉譯後為 <select>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@page "/InputSample"
<EditForm Model="@inputSampleModel">
    <InputSelect @bind-Value="inputSampleModel.SelectedValue">

        @foreach (var item in Options)
        {
            <option value="@item">@item</option>
        }
    </InputSelect>
</EditForm>

@code {
    private InputSampleModel inputSampleModel = new();

    private List<string> Options = new List<string>()
    {
        "Option1",
        "Option2",
        "Option3"
    };

    class InputSampleModel
    {
        public string SelectedValue { get; set; }
    }
}

小結

今日介紹五種內建輸入元件的用法,使用內建的輸入元件才可以支援表單<EditForm>的驗證,明天還說明剩下的四種輸入元件,以及如果這些內建元件都不合用該要怎麼客製化開發支援驗證的輸入元件