日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ASP.NET?Core中的Razor頁面使用視圖組件_基礎應用

作者:Sweet-Tang ? 更新時間: 2022-04-26 編程語言

視圖組件簡介

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

視圖組件特性:

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

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

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

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

創建視圖組件

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

視圖組件類

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

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

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

視圖組件類特性:

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

視圖組件方法

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

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

查找視圖路徑

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

  • Views//Components//
  • Views/Shared/Components//

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

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

調用視圖組件

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

    @Component.InvokeAsync("Name of view component", )

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

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

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

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

    
    

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

    
    

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

@addTagHelper *, MyWebApp

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

本示例中使用的InvokeAsync方法:

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

標簽幫助器標記:

    
    

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

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

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

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

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

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

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

添加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 InvokeAsync(int maxPriority, bool isDone)
        {
            var items = await GetItemsAsync(maxPriority, isDone);
            return View(items);
        }
        
        private Task> 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
    
    

    Priority Items

      @foreach (var todo in Model) {
    • @todo.Name
    • }
    Razor視圖會列出TodoItem并顯示它們。如果視圖組件InvokeAsync方法未傳遞視圖的名稱(如我們的示例中),則按照約定視圖名稱為?Default。在本文的后面,我將向您展示如何傳遞視圖的名稱。如果視圖組件只適用于特定控制器,則可以將其添加到控制器特定的文件夾(Views/Todo/Components/PriorityList/Default.cshtml)。
  • 在視圖?Views/Todo/index.cshtml?文件底部的div元素中包含視圖組件的調用
        
    @await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })

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

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

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

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

指定視圖名稱

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

    public async Task 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

PVC Named Priority Component View

@ViewBag.PriorityMessage

    @foreach (var todo in Model) {
  • @todo.Name
  • }

修改視圖?Views/TodoList/Index.cshtml:

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

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

如果顯示不是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?組件視圖。

避免字符串魔法

如果要編譯時安全,則可以使用類名替換硬編碼視圖組件名稱。創建沒有以“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 InvokeAsync(
        int maxPriority, bool isDone)
        {
            var items = await GetItemsAsync(maxPriority, isDone);
            return View(items);
        }
        private Task> 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

ToDo nameof

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

其它資源

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

原文鏈接:https://www.cnblogs.com/tdfblog/p/view-components-in-asp-net-core.html

欄目分類
最近更新