ログを入力できる画面はできましたが、ログは毎日書くという意味です。たった1件では足りません。ブログ(Blog)を追加しましょう。
まずBlogModelクラスを新規作成します。中身はシンプルで、Id、名前、ログリスト、作成日時の4つのプロパティだけです。
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 でリファクタリングされています。原文リンクからリファクタリング後のコードと比較しながら学習できます。ご覧いただきありがとうございます。原作者を応援してください。