ASP.NET Core Razor 視圖組件

視圖組件簡介

在新的ASP.NET Core MVC中,視圖組件類似於局部視圖,但它們更強大。視圖組件不使用模型綁定,僅依賴於您在調用時提供的數據。

視圖組件特性:

  • 呈現頁面響應的某一部分而不是整個響應
  • 包括在控制器和視圖之間發現的關注分離和可測試性優勢
  • 可以具有參數和業務邏輯
  • 通常在頁面佈局中調用

視圖組件是在任何地方可重用的呈現邏輯,對於局部視圖來說相對複雜,例如:

  • 動態導航菜單
  • 標籤雲(查詢數據庫)
  • 登錄面板
  • 購物車
  • 最近發表的文章
  • 典型博客上的側邊欄內容
  • 將在每個頁面上呈現的登錄面板,並顯示要註銷或登錄的鏈接,具體取決於用戶的登錄狀態

視圖組件由兩部分組成:類(通常繼承自ViewComponent)和返回的結果(通常是視圖)。像控制器一樣,視圖組件可以是POCO,但大多數開發人員都希望利用從ViewComponent繼承的方法和屬性。

創建視圖組件

此部分包含創建視圖組件的高級功能。在本文的後面,我們將詳細介紹每一個步驟,並創建一個視圖組件。

視圖組件類

視圖組件類可以通過以下任何方式來創建:

  • 繼承自 ViewComponent
  • 使用[ViewComponent]特性來標記一個類,或者繼承自具有[ViewComponent]特性的類
  • 創建類的名稱以 ViewComponent 後綴結尾

與控制器一樣,視圖組件必須是公共、非嵌套、非抽象類。視圖組件名稱是刪除“ViewComponent”後綴的類名稱,也可以使用ViewComponentAttribute.Name屬性顯式指定名稱。

視圖組件類特性:

  • 完美支持構造函數依賴注入
  • 不參與控制器生命週期,這意味着您不能在視圖組件中使用過濾器

視圖組件方法

視圖組件在InvokeAsync方法中定義邏輯,並返回IViewComponentResult類型。參數直接來自視圖組件的調用,而不是模型綁定;視圖組件從不直接處理請求;通常視圖組件會初始化模型,並通過調用View方法將其傳遞給視圖。總而言之,視圖組件方法特性:

  • 定義一個返回IViewComponentResultInvokeAsync方法
  • 通常會初始化一個模型,並通過調用ViewComponent類型的View方法將其傳遞給視圖
  • 參數來自調用方法,而不是HTTP請求,沒有模型綁定
  • 不能直接通過HTTP請求訪問,它們通常在視圖中通過代碼調用;視圖組件永遠不會處理請求
  • 在方法簽名上重載,而不是當前HTTP請求的任何詳細信息

查找視圖路徑

運行時在以下路徑中搜索視圖:

  • Views/<controller_name>/Components/<view_component_name>/<view_name>
  • Views/Shared/Components/<view_component_name>/<view_name>

視圖組件的視圖名稱默認爲Default,這意味着您的視圖文件通常將命名爲Default.cshtml。創建視圖組件結果或調用View方法時,可以指定不同的視圖名稱。

我們建議您視圖文件命名爲Default.cshtml,並使用Views/Shared/Components/<view_component_name>/ .cshtml路徑。此示例中使用的PriorityList視圖組件,視圖的路徑是Views/Shared/Components/PriorityList/Default.cshtml

調用視圖組件

要使用視圖組件,請在視圖中調用以下代碼:

    @Component.InvokeAsync("Name of view component", <anonymous type containing parameters>)

參數將被傳遞給InvokeAsync方法,在本文中編寫的PriorityList視圖組件在Views/Todo/Index.cshtml視圖文件中調用。在下文中,使用兩個參數調用InvokeAsync方法:

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

通過標籤幫助器調用視圖組件

對於ASP.NET Core 1.1及更高版本,您可以將視圖組件作爲標籤幫助器(Tag Helper)進行調用:

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

標籤幫助器將Pascal命名方式的類型和方法參數被轉換成它們的小寫短橫線命名方式(lower kebab case)。調用視圖組件的標籤幫助器使用該元素,視圖組件約定如下:

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

注意:爲了將視圖組件作爲標籤幫助器,您必須使用@addTagHelper指令註冊包含視圖組件的程序集。例如,如果您的視圖組件位於名爲“MyWebApp”的程序集中,請將以下指令添加到_ViewImports.cshtml文件中:

@addTagHelper *, MyWebApp

您可以將視圖組件作爲標籤幫助器註冊到引用視圖組件的任何文件。有關如何註冊標籤助手的更多信息,請參閱Managing Tag Helper Scope。

本示例中使用的InvokeAsync方法:

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

標籤幫助器標記:

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

在上面的示例中,PriorityList視圖組件變爲priority-list;視圖組件的參數作爲屬性按小寫短橫線命名方式傳遞。

從控制器直接調用視圖組件

視圖組件通常在視圖調用,但您也可以直接在控制器的方法中調用它們。雖然視圖組件被定義爲不能像控制器一樣直接處理請求,但您可以輕鬆在控制器的Action方法中實現返回ViewComponentResult內容。

在下面的示例中,在控制器直接調用視圖組件:

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

演練:創建一個簡單的視圖組件

示例下載,構建和測試入門代碼。這是一個簡單的項目,Todo控制器顯示 Todo 項目列表。

List of ToDos

添加ViewComponent類

創建一個 ViewComponents 文件夾並添加以下PriorityListViewComponent類:

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();
        }
        
    }
}

代碼注意事項:

  • 視圖組件類可以包含在項目中的任何文件夾中。
  • 因爲類名稱PriorityListViewComponent以後綴ViewComponent結尾,運行時在視圖中引用視圖組件時使用字符串“PriorityList”。稍後我會詳細解釋一下。
  • [ViewComponent]特性可以更改用於引用視圖組件的名稱。例如,我們可以該類命名爲XYZ並應用該ViewComponent屬性:

        [ViewComponent(Name = "PriorityList")]
        public class XYZ : ViewComponent
  • [ViewComponent]特性告訴視圖組件選擇器在查找與組件關聯的視圖時使用名稱PriorityList,並在從視圖引用組件類時使用字符串“PriorityList”。稍後我會詳細解釋一下。
  • 組件使用依賴注入來使DbContext可用。
  • InvokeAsync 是一個可以從視圖中調用的公開方法,它可以使用任意數量的參數。
  • InvokeAsync方法返回滿足isDonemaxPriority參數的ToDo集合。

創建視圖組件Razor視圖

  • 創建Views/Shared/Components文件夾,此文件夾必須命名爲 Components
  • 創建 Views/Shared/Components/PriorityList 文件夾。此文件夾名稱必須與視圖組件類的名稱一致,或者類名稱去掉後綴(如果遵循約定在類名稱中使用ViewComponent後綴)。如果您使用該ViewComponent特性,則名稱需要與特性名稱一致。
  • 創建一個Views/Shared/Components/PriorityList/Default.cshtml Razor視圖:

    @model IEnumerable<ViewComponentSample.Models.TodoItem>
    
    <h3>Priority Items</h3>
    <ul>
        @foreach (var todo in Model)
        {
            <li>@todo.Name</li>
        }
    </ul>
    Razor視圖會列出TodoItem並顯示它們。如果視圖組件InvokeAsync方法未傳遞視圖的名稱(如我們的示例中),則按照約定視圖名稱爲 Default。在本文的後面,我將向您展示如何傳遞視圖的名稱。如果視圖組件只適用於特定控制器,則可以將其添加到控制器特定的文件夾(Views/Todo/Components/PriorityList/Default.cshtml)。
  • 在視圖 Views/Todo/index.cshtml 文件底部的div元素中包含視圖組件的調用

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

@await Component.InvokeAsync是調用視圖組件的語法。第一個參數是我們要調用組件的名稱,隨後是傳遞給組件的參數。InvokeAsync可以包含任意數量的參數。

調試應用程序,下圖顯示了ToDo列表和選擇項:

todo list and priority items

您也可以直接在控制器中調用視圖組件:

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

priority items from IndexVC action

指定視圖名稱

複雜視圖組件可能需要在某些情況下指定非默認視圖。以下代碼顯示瞭如何從InvokeAsync方法中指定“PVC”視圖。修改PriorityListViewComponent類中的InvokeAsync方法。

    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 視圖文件。添加標題以表示正在使用的是PVC視圖。

@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/TodoList/Index.cshtml

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

運行應用程序並驗證是PVC視圖。

Priority View Component

如果顯示不是PVC視圖,請驗證您調用視圖組件priority參數是否爲4或更高的。

檢測視圖路徑

  • priority參數更改爲三個或更小,返回默認視圖。
  • 臨時將 Views/Todo/Components/PriorityList/Default.cshtml 重命名爲 1Default.cshtml
  • 調試應用程序,您將收到以下錯誤:

    An unhandled exception occurred while processing the request.
    InvalidOperationException: The view 'Components/PriorityList/Default' was not 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.cshtml
  • Shared 的Todo視圖組件視圖中添加一些標記,以表示視圖來自 Shared 文件夾。
  • 測試 Shared 組件視圖。

ToDo output with Shared component view

避免字符串魔法

如果要編譯時安全,則可以使用類名替換硬編碼視圖組件名稱。創建沒有以“ViewComponent”後綴的視圖組件:

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運算符:

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

<h2>ToDo nameof</h2>

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

其它資源

  • 依賴注入視圖
  • 查看或下載示例代碼

原文:《View components》https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components
翻譯:Sweet Tang
本文地址:http://www.cnblogs.com/tdfblog/p/view-components-in-asp-net-core.html
歡迎轉載,請在明顯位置給出出處及鏈接。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章