Blazor預設的寫法是Code Inline,他是將Html、Razor及C# Code全部寫在同一個檔案裡。 在邏輯比較單純的情況下,這樣寫並沒有太大問題。 但當程式碼複雜度提高之後,寫在一起可讀性就會很差。 因此在程式碼太複雜時,或是習慣webform的模式將Html及C# Code分開寫的人,就可以使用Code Behind的寫法。
1.建立一個Blazor元件同名稱的cs檔案,如:「BlogPost.razor.cs」,當命名一致時vs會將同名稱檔案自動結合在一起。如圗:

2.將C#類別名稱後面加上Base,如:BlogPostBase。並繼承ComponentBase後,將原本寫在前端的C# Code移動到cs檔案內。
using Microsoft.AspNetCore.Components;
namespace BlazorDemo.Pages;
public class BlogPostBase : ComponentBase
{
[Parameter]
public int Id { get; set; }
public string Content { get; set; } = null!;
protected override void OnInitialized()
{
Content = Id switch
{
1 => "前言",
2 => "簡介",
_ => string.Empty
};
}
}
3.繼承(@inherits)新建立的Code Behind類別,並將@Code{}區域移除。
@page "/blog/{Id:int}"
@inherits BlogPostBase
<div class="ms-auto pb-5">
@Content
</div>