ASP.NET Core 中的檢視元件View components in ASP.NET Core

作者:Rick AndersonBy Rick Anderson

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

檢視元件View components

檢視元件與部分檢視類似,但功能更強大。View components are similar to partial views, but they're much more powerful. 檢視元件不會使用模型繫結,並且只取決於呼叫它時所提供的資料。View components don't use model binding, and only depend on the data provided when calling into it. 此文章是使用控制器與檢視所撰寫,但檢視元件也能搭配 Razor Pages 使用。This article was written using controllers and views, but view components also work with Razor Pages.

檢視元件:A view component:

  • 轉譯區塊,而不是整個回應。Renders a chunk rather than a whole response.
  • 包含控制器與檢視之間的相同關注點分離和可測試性優點。Includes the same separation-of-concerns and testability benefits found between a controller and view.
  • 可以有參數和商務邏輯。Can have parameters and business logic.
  • 它通常是從配置頁面叫用。Is typically invoked from a layout page.

如果您的可重複使用轉譯邏輯對於部分檢視而言太過複雜,則檢視元件是處理它的預定位置,例如:View components are intended anywhere you have reusable rendering logic that's too complex for a partial view, such as:

  • 動態導覽功能表Dynamic navigation menus
  • 標籤雲端 (可在其中查詢資料庫)Tag cloud (where it queries the database)
  • 登入面板Login panel
  • 購物車Shopping cart
  • 最近發行的文章Recently published articles
  • 一般部落格上的資訊看板內容Sidebar content on a typical blog
  • 登入面板,將在每個頁面上轉譯並根據使用者登入狀態來示範登出或登入連結A login panel that would be rendered on every page and show either the links to log out or log in, depending on the log in state of the user

檢視元件是由兩個部分所組成:類別 (通常衍生自 ViewComponent) 以及它所傳回的結果 (通常是檢視)。A view component consists of two parts: the class (typically derived from ViewComponent) and the result it returns (typically a view). 與控制器類似,檢視元件可以是 POCO,但大部分開發人員會想要利用透過衍生自 ViewComponent 而取得的方法和屬性。Like controllers, a view component can be a POCO, but most developers will want to take advantage of the methods and properties available by deriving from ViewComponent.

當不確定檢視元件是否符合應用程式的規格時,您可以考慮改用 Razor 元件。When considering if view components meet an app's specifications, consider using Razor Components instead. Razor 元件同樣會結合標記與 C# 程式碼,來產生可重複使用的 UI 單元。Razor Components also combine markup with C# code to produce reusable UI units. Razor 元件是為提升開發人員提供用戶端 UI 邏輯和組合時的生產力所設計。Razor Components are designed for developer productivity when providing client-side UI logic and composition. 如需詳細資訊,請參閱 建立和使用 ASP.NET Core Razor 元件For more information, see 建立和使用 ASP.NET Core Razor 元件.

建立檢視元件Creating a view component

本節包含建立檢視元件的高階需求。This section contains the high-level requirements to create a view component. 在本文稍後,我們會詳細檢查每個步驟,並建立檢視元件。Later in the article, we'll examine each step in detail and create a view component.

檢視元件類別The view component class

您可以透過下列任一項來建立檢視元件類別:A view component class can be created by any of the following:

  • 衍生自 ViewComponentDeriving from ViewComponent
  • [ViewComponent] 屬性裝飾類別,或衍生自具有 [ViewComponent] 屬性的類別Decorating a class with the [ViewComponent] attribute, or deriving from a class with the [ViewComponent] attribute
  • 建立名稱結尾為尾碼 ViewComponent 的類別Creating a class where the name ends with the suffix ViewComponent

與控制器類似,檢視元件必須是公用、非巢狀和非抽象類別。Like controllers, view components must be public, non-nested, and non-abstract classes. 檢視元件名稱是移除 "ViewComponent" 尾碼的類別名稱。The view component name is the class name with the "ViewComponent" suffix removed. 它也可以使用 ViewComponentAttribute.Name 屬性明確地指定。It can also be explicitly specified using the ViewComponentAttribute.Name property.

檢視元件類別:A view component class:

  • 完全支援建構函式相依性插入Fully supports constructor dependency injection

  • 不參與控制器生命週期,這表示您無法在檢視元件中使用篩選Doesn't take part in the controller lifecycle, which means you can't use filters in a view component

檢視元件方法View component methods

檢視元件會在傳回 Task<IViewComponentResult>InvokeAsync 方法或傳回 IViewComponentResult 的同步 Invoke 方法中定義其邏輯。A view component defines its logic in an InvokeAsync method that returns a Task<IViewComponentResult> or in a synchronous Invoke method that returns an IViewComponentResult. 參數直接來自檢視元件的引動過程,而不是來自模型繫結。Parameters come directly from invocation of the view component, not from model binding. 檢視元件絕不會直接處理要求。A view component never directly handles a request. 通常,檢視元件會初始化模型,並呼叫 View 方法將其傳遞至檢視。Typically, a view component initializes a model and passes it to a view by calling the View method. 簡要來說,檢視元件方法:In summary, view component methods:

  • 定義傳回 Task<IViewComponentResult>InvokeAsync 方法或傳回 IViewComponentResult 的同步 Invoke 方法。Define an InvokeAsync method that returns a Task<IViewComponentResult> or a synchronous Invoke method that returns an IViewComponentResult.
  • 通常會初始化模型,並呼叫 ViewComponent View 方法將其傳遞至檢視。Typically initializes a model and passes it to a view by calling the ViewComponent View method.
  • 參數來自呼叫端方法,而非 HTTP。Parameters come from the calling method, not HTTP. 沒有模型繫結。There's no model binding.
  • 無法直接當成 HTTP 端點連接。Are not reachable directly as an HTTP endpoint. 它們是透過您的程式碼所叫用 (通常是在檢視中)。They're invoked from your code (usually in a view). 檢視元件絕不會處理要求。A view component never handles a request.
  • 已多載在簽章上,而非目前 HTTP 要求中的任何詳細資料。Are overloaded on the signature rather than any details from the current HTTP request.

檢視搜尋路徑View search path

執行階段會搜尋下列路徑中的檢視:The runtime searches for the view in the following paths:

  • /Views/{控制器名稱}/Components/{檢視元件名稱}/{檢視名稱}/Views/{Controller Name}/Components/{View Component Name}/{View Name}
  • /Views/Shared/Components/{檢視元件名稱}/{檢視名稱}/Views/Shared/Components/{View Component Name}/{View Name}
  • /Pages/Shared/Components/{檢視元件名稱}/{檢視名稱}/Pages/Shared/Components/{View Component Name}/{View Name}

搜尋路徑適用於使用控制器 + 檢視和 Razor Pages 的專案。The search path applies to projects using controllers + views and Razor Pages.

檢視元件的預設檢視名稱是 Default,這表示您的檢視檔案通常會命名為 Default.cshtmlThe default view name for a view component is Default, which means your view file will typically be named Default.cshtml. 建立檢視元件結果時,或呼叫 View 方法時,可以指定不同的檢視名稱。You can specify a different view name when creating the view component result or when calling the View method.

建議您將檢視檔案命名為 Default.cshtml,並使用 Views/Shared/Components/{View Component Name}/{View Name} 路徑。We recommend you name the view file Default.cshtml and use the Views/Shared/Components/{View Component Name}/{View Name} path. 此範例中所使用的 PriorityList 檢視元件會將 Views/Shared/Components/PriorityList/Default.cshtml 用於檢視元件檢視。The PriorityList view component used in this sample uses Views/Shared/Components/PriorityList/Default.cshtml for the view component view.

叫用檢視元件Invoking a view component

若要使用檢視元件,請在檢視內呼叫下列項目:To use the view component, call the following inside a view:

@await Component.InvokeAsync("Name of view component", {Anonymous Type Containing Parameters})

參數將傳遞給 InvokeAsync 方法。The parameters will be passed to the InvokeAsync method. 本文中所開發的 PriorityList 檢視元件是透過 Views/ToDO/Index.cshtml 檢視檔案所叫用。The PriorityList view component developed in the article is invoked from the Views/ToDo/Index.cshtml view file. 在下列範例中,InvokeAsync 方法是使用兩個參數所呼叫:In the following, the InvokeAsync method is called with two parameters:

@await Component.InvokeAsync("PriorityList", new { maxPriority = 4, isDone = true })

叫用檢視元件作為標籤協助程式Invoking a view component as a Tag Helper

針對 ASP.NET Core 1.1 和更新版本,您可以叫用檢視元件作為標籤協助程式For ASP.NET Core 1.1 and higher, you can invoke a view component as a Tag Helper:

<vc:priority-list max-priority="2" is-done="false">
</vc:priority-list>

標籤協助程式依照 Pascal 命名法大小寫慣例的類別和方法參數會轉譯成其 Kebab 字體Pascal-cased class and method parameters for Tag Helpers are translated into their kebab case. 用來叫用檢視元件的標籤協助程式會使用 <vc></vc> 項目。The Tag Helper to invoke a view component uses the <vc></vc> element. 檢視元件指定如下:The view component is specified as follows:

<vc:[view-component-name]
  parameter1="parameter1 value"
  parameter2="parameter2 value">
</vc:[view-component-name]>

若要使用檢視元件作為標籤協助程式,請使用 @addTagHelper 指示詞註冊包含檢視元件的組件。To use a view component as a Tag Helper, register the assembly containing the view component using the @addTagHelper directive. 如果檢視元件位於稱為 MyWebApp 的組件中,則請將下列指示詞新增至 _ViewImports.cshtml 檔案:If your view component is in an assembly called MyWebApp, add the following directive to the _ViewImports.cshtml file:

@addTagHelper *, MyWebApp

您可以將檢視元件註冊為任何參考檢視元件的檔案標籤協助程式。You can register a view component as a Tag Helper to any file that references the view component. 如需如何註冊標籤協助程式的詳細資訊,請參閱管理標籤協助程式範圍See Managing Tag Helper Scope for more information on how to register Tag Helpers.

本教學課程中使用的 InvokeAsync 方法:The InvokeAsync method used in this tutorial:

@await Component.InvokeAsync("PriorityList", new { maxPriority = 4, isDone = true })

在標籤 (tag) 協助程式標籤 (markup) 中:In Tag Helper markup:

<vc:priority-list max-priority="2" is-done="false">
</vc:priority-list>

在上述範例中,PriorityList 檢視元件會變成 priority-listIn the sample above, the PriorityList view component becomes priority-list. 檢視元件的參數會以 Kebab 字體傳遞為屬性。The parameters to the view component are passed as attributes in kebab case.

直接從控制器叫用檢視元件Invoking a view component directly from a controller

檢視元件通常是從檢視中進行叫用,但您可以直接從控制器方法叫用它們。View components are typically invoked from a view, but you can invoke them directly from a controller method. 雖然檢視元件不會定義控制器這類端點,但您可以輕鬆地實作控制器動作,以傳回 ViewComponentResult 的內容。While view components don't define endpoints like controllers, you can easily implement a controller action that returns the content of a ViewComponentResult.

在此範例中,是直接從控制器呼叫檢視元件:In this example, the view component is called directly from the controller:

public IActionResult IndexVC()
{
    return ViewComponent("PriorityList", new { maxPriority = 3, isDone = false });
}

逐步解說:建立簡單的檢視元件Walkthrough: Creating a simple view component

下載、建置和測試起始程式碼。Download, build and test the starter code. 它是具有 ToDo 控制器的簡單專案,而此控制器顯示 ToDO 項目清單。It's a simple project with a ToDo controller that displays a list of ToDo items.

ToDos 清單

新增 ViewComponent 類別Add a ViewComponent class

建立 ViewComponents 資料夾,並新增下列 PriorityListViewComponent 類別:Create a ViewComponents folder and add the following PriorityListViewComponent class:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewComponentSample.Models;

namespace ViewComponentSample.ViewComponents
{
    public class PriorityListViewComponent : ViewComponent
    {
        private readonly ToDoContext db;

        public PriorityListViewComponent(ToDoContext context)
        {
            db = context;
        }

        public async Task<IViewComponentResult> InvokeAsync(
        int maxPriority, bool isDone)
        {
            var items = await GetItemsAsync(maxPriority, isDone);
            return View(items);
        }
        private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
        {
            return db.ToDo.Where(x => x.IsDone == isDone &&
                                 x.Priority <= maxPriority).ToListAsync();
        }
    }
}

程式碼的注意事項:Notes on the code:

  • 檢視元件類別可以包含在專案的任何資料夾中。View component classes can be contained in any folder in the project.

  • 因為類別名稱 PriorityListViewComponent 結尾為尾碼 ViewComponent,所以從檢視參考類別元件時,執行階段會使用字串 "PriorityList"。Because the class name PriorityListViewComponent ends with the suffix ViewComponent, the runtime will use the string "PriorityList" when referencing the class component from a view. 我稍後將更詳細地進行說明。I'll explain that in more detail later.

  • [ViewComponent] 屬性可以變更用來參考檢視元件的名稱。The [ViewComponent] attribute can change the name used to reference a view component. 例如,我們無法將類別命名為 XYZ 以及套用 ViewComponent 屬性:For example, we could've named the class XYZ and applied the ViewComponent attribute:

    [ViewComponent(Name = "PriorityList")]
       public class XYZ : ViewComponent
    
  • 上面的 [ViewComponent] 屬性會告知檢視元件選取器在尋找與元件建立關聯的檢視時使用名稱 PriorityList,以及在從檢視參考類別元件時使用字串 "PriorityList"。The [ViewComponent] attribute above tells the view component selector to use the name PriorityList when looking for the views associated with the component, and to use the string "PriorityList" when referencing the class component from a view. 我稍後將更詳細地進行說明。I'll explain that in more detail later.

  • 元件會使用相依性插入,讓資料內容可供使用。The component uses dependency injection to make the data context available.

  • InvokeAsync 會公開可以從檢視中呼叫的方法,而且可以採用任意數目的引數。InvokeAsync exposes a method which can be called from a view, and it can take an arbitrary number of arguments.

  • InvokeAsync 方法會傳回一組符合 isDonemaxPriority 參數的 ToDo 項目。The InvokeAsync method returns the set of ToDo items that satisfy the isDone and maxPriority parameters.

建立檢視元件 Razor 檢視Create the view component Razor view

  • 建立 Views/Shared/Components 資料夾。Create the Views/Shared/Components folder. 此資料夾必須命名為 ComponentsThis folder must be named Components.

  • 建立 Views/Shared/Components/PriorityList 資料夾。Create the Views/Shared/Components/PriorityList folder. 此資料夾名稱必須符合檢視元件類別的名稱,或去掉尾碼的類別名稱 (如果我們遵循慣例,並在類別名稱中使用 ViewComponent 尾碼)。This folder name must match the name of the view component class, or the name of the class minus the suffix (if we followed convention and used the ViewComponent suffix in the class name). 如果您已使用 ViewComponent 屬性,則類別名稱需要符合屬性指定。If you used the ViewComponent attribute, the class name would need to match the attribute designation.

  • 建立 Views/Shared/Components/PriorityList/Default.cshtml Razor 檢視:Create a Views/Shared/Components/PriorityList/Default.cshtml Razor view:

    @model IEnumerable<ViewComponentSample.Models.TodoItem>
    
    <h3>Priority Items</h3>
    <ul>
        @foreach (var todo in Model)
        {
            <li>@todo.Name</li>
        }
    </ul>
    

    Razor 檢視採用 TodoItem 清單,並加以顯示。The Razor view takes a list of TodoItem and displays them. 如果檢視元件 InvokeAsync 方法未傳遞檢視名稱 (如我們的範例所示),則依照慣例會使用 Default 作為檢視名稱。If the view component InvokeAsync method doesn't pass the name of the view (as in our sample), Default is used for the view name by convention. 在教學課程稍後,我將示範如何傳遞檢視的名稱。Later in the tutorial, I'll show you how to pass the name of the view. 若要覆寫特定控制器的預設樣式,請在控制器特定檢視資料夾中新增檢視 (例如 Views/ToDO/Components/PriorityList/Default.cshtml)。To override the default styling for a specific controller, add a view to the controller-specific view folder (for example Views/ToDo/Components/PriorityList/Default.cshtml).

    如果檢視元件是控制器特有的,則可以將它新增至控制器特定資料夾 (Views/ToDO/Components/PriorityList/Default.cshtml)。If the view component is controller-specific, you can add it to the controller-specific folder (Views/ToDo/Components/PriorityList/Default.cshtml).

  • 將包含優先順序清單元件呼叫的 div 新增至 Views/ToDO/index.cshtml 檔案底端:Add a div containing a call to the priority list component to the bottom of the Views/ToDo/index.cshtml file:

    </table>
    <div>
        @await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })
    </div>
    

@await Component.InvokeAsync 標記顯示呼叫檢視元件的語法。The markup @await Component.InvokeAsync shows the syntax for calling view components. 第一個引數是我們想要叫用或呼叫之元件的名稱。The first argument is the name of the component we want to invoke or call. 後續參數會傳遞至元件。Subsequent parameters are passed to the component. InvokeAsync 可以採用任意數目的引數。InvokeAsync can take an arbitrary number of arguments.

測試應用程式。Test the app. 下圖顯示 ToDo 清單和優先順序項目:The following image shows the ToDo list and the priority items:

ToDo 清單和優先順序項目

您也可以直接從控制器呼叫檢視元件:You can also call the view component directly from the controller:

public IActionResult IndexVC()
{
    return ViewComponent("PriorityList", new { maxPriority = 3, isDone = false });
}

IndexVC 動作中的優先順序項目

指定檢視名稱Specifying a view name

在某些情況下,可能需要複雜的檢視元件,才能指定非預設檢視。A complex view component might need to specify a non-default view under some conditions. 下列程式碼示範如何從 InvokeAsync 方法指定 "PVC" 檢視。The following code shows how to specify the "PVC" view from the InvokeAsync method. 更新 PriorityListViewComponent 類別中的 InvokeAsync 方法。Update the InvokeAsync method in the PriorityListViewComponent class.

public async Task<IViewComponentResult> InvokeAsync(
    int maxPriority, bool isDone)
{
    string MyView = "Default";
    // If asking for all completed tasks, render with the "PVC" view.
    if (maxPriority > 3 && isDone == true)
    {
        MyView = "PVC";
    }
    var items = await GetItemsAsync(maxPriority, isDone);
    return View(MyView, items);
}

Views/Shared/Components/PriorityList/Default.cshtml 檔案複製至名為 Views/Shared/Components/PriorityList/PVC.cshtml 的檢視。Copy the Views/Shared/Components/PriorityList/Default.cshtml file to a view named Views/Shared/Components/PriorityList/PVC.cshtml. 新增標題,以指出正在使用 PVC 檢視。Add a heading to indicate the PVC view is being used.

@model IEnumerable<ViewComponentSample.Models.TodoItem>

<h2> PVC Named Priority Component View</h2>
<h4>@ViewBag.PriorityMessage</h4>
<ul>
    @foreach (var todo in Model)
    {
        <li>@todo.Name</li>
    }
</ul>

更新 Views/ToDO/Index.cshtmlUpdate Views/ToDo/Index.cshtml:

@await Component.InvokeAsync("PriorityList", new { maxPriority = 4, isDone = true })

執行應用程式,並驗證 PVC 檢視。Run the app and verify PVC view.

設定檢視元件優先順序

如果未轉譯 PVC 檢視,請驗證您要呼叫的檢視元件優先順序為 4 或以上。If the PVC view isn't rendered, verify you are calling the view component with a priority of 4 or higher.

檢查檢視路徑Examine the view path

  • 將優先順序參數變更為 3 或更小,以不傳回優先順序檢視。Change the priority parameter to three or less so the priority view isn't returned.

  • Views/ToDO/Components/PriorityList/Default.cshtml 暫時重新命名為 1Default.cshtmlTemporarily rename the Views/ToDo/Components/PriorityList/Default.cshtml to 1Default.cshtml.

  • 測試應用程式,您會收到下列錯誤:Test the app, you'll get the following error:

    An unhandled exception occurred while processing the request.
    InvalidOperationException: The view 'Components/PriorityList/Default' wasn't found. The following locations were searched:
    /Views/ToDo/Components/PriorityList/Default.cshtml
    /Views/Shared/Components/PriorityList/Default.cshtml
    EnsureSuccessful
    
  • Views/ToDO/Components/PriorityList/1Default.cshtml 複製至 Views/Shared/Components/PriorityList/Default.cshtmlCopy Views/ToDo/Components/PriorityList/1Default.cshtml to Views/Shared/Components/PriorityList/Default.cshtml.

  • 將某個標記新增至 Shared ToDO 檢視元件檢視,指出檢視來自 Shared 資料夾。Add some markup to the Shared ToDo view component view to indicate the view is from the Shared folder.

  • 測試 Shared 元件檢視。Test the Shared component view.

含 Shared 元件檢視的 ToDo 輸出

避免硬式編碼的字串Avoiding hard-coded strings

如果您想要編譯時間安全,則可以將寫在程式碼中的檢視元件名稱取代為類別名稱。If you want compile time safety, you can replace the hard-coded view component name with the class name. 建立不含 "ViewComponent" 尾碼的檢視元件:Create the view component without the "ViewComponent" suffix:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewComponentSample.Models;

namespace ViewComponentSample.ViewComponents
{
    public class PriorityList : ViewComponent
    {
        private readonly ToDoContext db;

        public PriorityList(ToDoContext context)
        {
            db = context;
        }

        public async Task<IViewComponentResult> InvokeAsync(
        int maxPriority, bool isDone)
        {
            var items = await GetItemsAsync(maxPriority, isDone);
            return View(items);
        }
        private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
        {
            return db.ToDo.Where(x => x.IsDone == isDone &&
                                 x.Priority <= maxPriority).ToListAsync();
        }
    }
}

using 陳述式新增至 Razor 檢視檔案,並使用 nameof 運算子:Add a using statement to your Razor view file, and use the nameof operator:

@using ViewComponentSample.Models
@using ViewComponentSample.ViewComponents
@model IEnumerable<TodoItem>

    <h2>ToDo nameof</h2>
    <!-- Markup removed for brevity.  -->

    <div>

        @*
            Note: 
            To use the below line, you need to #define no_suffix in ViewComponents/PriorityList.cs or it won't compile.
            By doing so it will cause a problem to index as there will be multiple viewcomponents 
            with the same name after the compiler removes the suffix "ViewComponent"
        *@

        @*@await Component.InvokeAsync(nameof(PriorityList), new { maxPriority = 4, isDone = true })*@
    </div>

執行同步工作Perform synchronous work

如果您不需要執行非同步工作,架構會處理叫用同步 Invoke 方法。The framework handles invoking a synchronous Invoke method if you don't need to perform asynchronous work. 下列方法會建立同步 Invoke 檢視元件:The following method creates a synchronous Invoke view component:

public class PriorityList : ViewComponent
{
    public IViewComponentResult Invoke(int maxPriority, bool isDone)
    {
        var items = new List<string> { $"maxPriority: {maxPriority}", $"isDone: {isDone}" };
        return View(items);
    }
}

檢視元件的 Razor 檔案,會列出傳遞至 Invoke 方法 (Views/Home/Components/PriorityList/Default.cshtml) 的字串:The view component's Razor file lists the strings passed to the Invoke method (Views/Home/Components/PriorityList/Default.cshtml):

@model List<string>

<h3>Priority Items</h3>
<ul>
    @foreach (var item in Model)
    {
        <li>@item</li>
    }
</ul>

使用下列其中一項方式,在 Razor 檔案中叫用檢視元件 (例如 Views/Home/Index.cshtml):The view component is invoked in a Razor file (for example, Views/Home/Index.cshtml) using one of the following approaches:

若要使用 IViewComponentHelper 方法,請呼叫 Component.InvokeAsyncTo use the IViewComponentHelper approach, call Component.InvokeAsync:

使用 IViewComponentHelper 在 Razor 檔案中叫用檢視元件 (例如 Views/Home/Index.cshtml)。The view component is invoked in a Razor file (for example, Views/Home/Index.cshtml) with IViewComponentHelper.

呼叫 Component.InvokeAsyncCall Component.InvokeAsync:

@await Component.InvokeAsync(nameof(PriorityList), new { maxPriority = 4, isDone = true })

若要使用標籤協助程式,請使用 @addTagHelper 指示詞註冊包含檢視元件的組件 (檢視元件位於稱為 MyWebApp 的組件中):To use the Tag Helper, register the assembly containing the View Component using the @addTagHelper directive (the view component is in an assembly called MyWebApp):

@addTagHelper *, MyWebApp

使用 Razor 標記檔案中的檢視元件標籤協助程式:Use the view component Tag Helper in the Razor markup file:

<vc:priority-list max-priority="999" is-done="false">
</vc:priority-list>

PriorityList.Invoke 的方法簽章為同步,但 Razor 會在標記檔案中找到並使用 Component.InvokeAsync 呼叫該方法。The method signature of PriorityList.Invoke is synchronous, but Razor finds and calls the method with Component.InvokeAsync in the markup file.

所有檢視元件參數均為必要參數All view component parameters are required

檢視元件中的每個參數都是必要屬性。Each parameter in a view component is a required attribute. 請參閱這個 GitHub 問題See this GitHub issue. 若省略了任何參數:If any parameter is omitted:

  • InvokeAsync 方法簽章即不相符,因此系統不會執行此方法。The InvokeAsync method signature won't match, therefore the method won't execute.
  • ViewComponent 不會轉譯任何標記。The ViewComponent won't render any markup.
  • 系統不會擲回任何錯誤。No errors will be thrown.

其他資源Additional resources