Blazor(15)-輸入元件(1)

前面在介紹資料綁定(Binding)的時候其實就已經有用到文字輸入的元件了, 那除了文字輸入以外,還有很多內建的輸入元件可以使用,像是:RadioBtn、Checkbox、Calendar等等。 都是browser內鍵就有的元件。今天會介紹一些常用的輸入元件,並把這些輸入元件擴充到留言板讓留言的項目更完整。

實作前處理

因為要把輸入元件擴充到留言板內,因此需先將留言資料擴充成DTO(資料傳輸物件)。 因此我們需要建立CommentModel來放置留言資料,並將文章及留言版所傳遞的參數都改為<List<CommentModel>>。 接著把原本的輸入框綁定到Comments的內文(Content)中。

<div class="comments">
    @foreach (var comment in Comments)
    {
        <div class="comment-content">
            @comment
        </div>
    }
    <div class="post-comment">
        <input type="button" @onclick=ButtonOnClick value="送出" />
    </div>
</div>

@code {
    [Parameter]public List<CommentModel> Comments { get; set; } = new();

    public CommentModel Preview { get; set; } = new();

    [Parameter]public EventCallback<List<CommentModel>> ButtonClick { get; set; }

    protected async Task ButtonOnClick()
    {
        Comments.Add(Preview);

        Preview = new();

        await ButtonClick.InvokeAsync(Comments);
    }

    public class CommentModel
    {
    }
}

Comment.razor

public class BlogPostBase : ComponentBase
{
    ...
    public List<CommentModel> Comments { get; set; } = new();
    ...
    protected void ButtonOnClick(List<CommentModel> comments)
    {
        ...
    }
}

BlogPost.razor.cs

TextBox

最常用的輸入元件,大家最熟悉的文字輸入,前面用來輸入文章內容的元件就是Textbox。 使用<input>,若沒有指定type時預設就是Textbox。 這邊會新增文字框來輸入留言人姓名。

<p class="m-0">姓名</p>
<input type="text" @bind=Preview.Name />

@code
{
    public CommentModel Preview { get; set; } = new();

    public class CommentModel
    {
        public string Name { get; set; } = null!;
    }
}

TextArea

與TextBox一樣是文字輸入框,不同的是,TextBox只允許單行輸入,而TextArea是多行文字輸入元件。 這邊新增一個多行文字框來輸入留言內容。

<p class="m-0">留言內容</p>
<textarea @bind="Preview.Content" type="text" class="form-control" />

@code
{
    public CommentModel Preview { get; set; } = new();

    public class CommentModel
    {
        public string Name { get; set; } = null!;

        public string Content { get; set; } = null!;
    }
}
An unhandled error has occurred. Reload 🗙