1. 程式人生 > 其它 >ASP.NET Core – Razor Class Library (RCL)

ASP.NET Core – Razor Class Library (RCL)

前言

Razor Class Library 的用途是封裝 Razor views, pages, controllers, page models, Razor components, View components, and data models, 到一個獨立的 Library, 然後 share with multiple projects.

以前介紹 Identity – Introduction & Scaffold  的時候就有提到過, ASP.NET Core 封裝了一些 Login, User Management 的 Pages, 方便我們快速啟動 Identity.

官網的例子更多是用在 Blozor + Razor components. 但是我沒有用 Blozor 和 Razor components. 我只用 Razor pages 和 View component.

所以這篇給的例子是 Razor Pages + View Component.

參考

Docs – Create reusable UI using the Razor class library project in ASP.NET Core

Docs – Consume ASP.NET Core Razor components from a Razor class library (RCL)

建立專案

1 個 web app, 一個 library.

mkdir TestRazorClassLibrary
cd TestRazorClassLibrary
dotnet new razorclasslib -o MyRazorLibrary --support-pages-and-views
dotnet new webapp -o MyWebApp
dotnet add MyWebApp reference MyRazorLibrary

注意: new razorclasslib 需要新增 --support-pages-and-views, 因為我要 share 的是 View Component.

最後一行是新增 reference, 因為 library 沒有釋出到 nuget.

建立 View Component in Library

用 VS Code 開啟 TestRazorClassLibrary folder

把 build-in 建立的 Area 洗掉, 建立 component folder

HelloWorldViewComponent.cs

using Microsoft.AspNetCore.Mvc;

namespace MyRazorLibrary;

public class HelloWorldViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        return View("~/Component/HelloWorld/Index.cshtml");
    }
}

Index.cshtml

<h1>Hello World</h1>

呼叫 View Component in Web App

Index.cshtml

@page
@model IndexModel
@addTagHelper *, MyRazorLibrary

@{
  ViewData["Title"] = "Home page";
}

<div class="text-center">
  <h1 class="display-4">Welcome</h1>
  <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<vc:hello-world></vc:hello-world>
View Code

執行

dotnet watch run --project MyWebApp

效果