在ASP.NET CORE中利用型別配置Layout

Likol Lee
Likol Lee
Nov 5 · 3 min read

[2019/11/07 更新] 範例程式碼可參考:https://github.com/twlikol/TypedLayout

前言

在.NET4.0的版本,通常是利用MasterPage或是UserControl來處理畫面的配置,而這些設定基本上是沒有非常緊密的整合,往往是需要透過路徑的方式來指定。

Razor Pages

在一個RazorPage的頁面中包含了一個.cshtml與.cs,cshtml也就是View而.cs就是Model,View是透過@model來指定對應的Model,而Model的部分則是繼承至Microsoft.AspNetCore.Mvc.RazorPages.PageModel。

為了要區隔不同頁的配置方式,因此我額外的定義一些繼承PageModel的型別:

  1. ListPage 用於一般資料列表的頁面
  2. ItemPage 用於單一筆資料維護頁面

當Page被載入時就可以根據Model的型別來指定對應的Layout

Layout

Layout是由一個.cshtml構成,並沒有.cs可以指定它的行為,但是可以透過@inherits來指定繼承的型別。

透過ILSpy可以觀察到當Layout頁面編譯後,它會繼承Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>,因此ListPageLayout<TModel>也需要繼承Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>。

實作

透過上述的資訊,就可以在ViewStart中定義全域的Layout設定。

PageLayoutManager

透過DI的方式註冊PageLayoutManager,初始化時透過ApplicationPartManager找到所有在組件中可以使用的Layout型別,再根據繼承的型別進行PageModel的型別對應。

[其他文章]

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade