現在我們有一個可以輸入日誌的介面了,但日誌就是每天都要寫的意思,只有一篇怎麼夠呢?我們來加上 blog。
首先新增BlogModel類,裡面很簡單只有 4 個屬性,分別為 Id、名稱、日誌列表及新增時間。
using System.ComponentModel.DataAnnotations;
namespace BlazorServer.Models;
public class BlogModel
{
[Key] public int Id { get; set; }
[MaxLength(10, ErrorMessage = "博客名称太长")]
public string? Name { get; set; }
public List<PostModel>? Posts { get; set; }
public DateTime CreateDateTime { get; set; }
}
接著將Post.razor的@page指示詞跟EditForm底下的 Expander 案例移除,打開launchSettings.json將launchUrl改為 Blog,因為我們的首頁要改成 Blog。

再把PostBase的OnInitializedAsync中指派值給Post的部分移除,Post上面加入Parameter,表示要從外部傳進來。

最後新增BlogBase.cs跟Blog.razor,可以看到BlogBase.cs的OnInitializedAsync呼叫一個方法LoadData,實體化一個Blog,裡面的Posts有 4 條資料。
using BlazorServer.Models;
using Microsoft.AspNetCore.Components;
namespace BlazorServer.Pages;
public class BlogBase : ComponentBase
{
public BlogModel? Blog { get; set; }
protected override Task OnInitializedAsync()
{
LoadData();
return base.OnInitializedAsync();
}
private void LoadData()
{
Blog = new BlogModel
{
Id = 1,
Name = "我的部落格",
Posts = new List<PostModel>
{
new PostModel
{ Id = 1, Title = "標題1", Content = "內容1", CreateDateTime = new(2021, 12, 11, 10, 20, 50) },
new PostModel { Id = 1, Title = "標題2", Content = "內容2", CreateDateTime = new(2021, 12, 12, 9, 13, 15) },
new PostModel
{ Id = 1, Title = "標題3", Content = "內容3", CreateDateTime = new(2021, 12, 13, 20, 31, 26) },
new PostModel { Id = 1, Title = "標題4", Content = "內容4", CreateDateTime = new(2021, 12, 14, 22, 15, 27) }
},
CreateDateTime = new(2021, 12, 14, 23, 46, 59)
};
}
}
Blog.razor則是如下圖一樣,要記住Blog==null的判斷很重要,因為真實的資料大都會用非同步方式傳遞,所以取得資料的速度會比畫面渲染的時間晚,若沒有這樣判斷,很容易發生 Blazor 找不到該資料而報錯的狀況。

另外Post.razor也做了相應調整,可以看到畫面呈現了部落格名稱及 4 條日誌,這樣一來我們就完成了簡單的部落格雛型了。
Post.razor:
@inherits PostBase
<div class="form-group">
<label for="CreateDateTime">创建时间</label>
<input
type="text"
@bind="Post!.CreateDateTime"
@bind:format="yyyy-MM-dd HH:mm:ss"
id="CreateDateTime"
class="form-control"
/>
</div>
<EditForm EditContext="EditContext">
<DataAnnotationsValidator />
<ValidationSummary />
@*<InputNumber @bind-Value="Post!.Id" class="form-control"></InputNumber>*@
<div class="form-group">
<label for="title">标题</label>
<input
type="text"
@bind="Post!.Title"
@bind:event="oninput"
id="title"
class="form-control"
/>
</div>
<div class="form-group">
<label for="content">内容</label>
<InputTextArea
@bind-Value="Post!.Content"
id="content"
class="form-control"
rows="8"
></InputTextArea>
</div>
<MyButton
ButtonType="submit"
ButtonClass="btn btn-info"
ButtonName="Submit"
></MyButton>
<MyButton
ButtonType="reset"
ButtonClass="btn btn-danger"
ButtonName="Reset"
></MyButton>
</EditForm>


引用:
註:本文程式碼透過 .NET 6 + Visual Studio 2022 重構,可點選原文連結與重構後程式碼比較學習,謝謝閱讀,支持原作者