日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core Razor 视图组件

發(fā)布時間:2023/12/4 asp.net 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core Razor 视图组件 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

視圖組件簡介

在新的ASP.NET Core MVC中,視圖組件類似于局部視圖,但它們更強(qiáng)大。視圖組件不使用模型綁定,僅依賴于您在調(diào)用時提供的數(shù)據(jù)。

視圖組件特性:

  • 呈現(xiàn)頁面響應(yīng)的某一部分而不是整個響應(yīng)

  • 包括在控制器和視圖之間發(fā)現(xiàn)的關(guān)注分離和可測試性優(yōu)勢

  • 可以具有參數(shù)和業(yè)務(wù)邏輯

  • 通常在頁面布局中調(diào)用

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

  • 動態(tài)導(dǎo)航菜單

  • 標(biāo)簽云(查詢數(shù)據(jù)庫)

  • 登錄面板

  • 購物車

  • 最近發(fā)表的文章

  • 典型博客上的側(cè)邊欄內(nèi)容

  • 將在每個頁面上呈現(xiàn)的登錄面板,并顯示要注銷或登錄的鏈接,具體取決于用戶的登錄狀態(tài)

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

創(chuàng)建視圖組件

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

視圖組件類

視圖組件類可以通過以下任何方式來創(chuàng)建:

  • 繼承自?ViewComponent?類

  • 使用[ViewComponent]特性來標(biāo)記一個類,或者繼承自具有[ViewComponent]特性的類

  • 創(chuàng)建類的名稱以?ViewComponent?后綴結(jié)尾

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

視圖組件類特性:

  • 完美支持構(gòu)造函數(shù)依賴注入

  • 不參與控制器生命周期,這意味著您不能在視圖組件中使用過濾器

視圖組件方法

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

  • 定義一個返回IViewComponentResult的InvokeAsync方法

  • 通常會初始化一個模型,并通過調(diào)用ViewComponent類型的View方法將其傳遞給視圖

  • 參數(shù)來自調(diào)用方法,而不是HTTP請求,沒有模型綁定

  • 不能直接通過HTTP請求訪問,它們通常在視圖中通過代碼調(diào)用;視圖組件永遠(yuǎn)不會處理請求

  • 在方法簽名上重載,而不是當(dāng)前HTTP請求的任何詳細(xì)信息

查找視圖路徑

運(yùn)行時在以下路徑中搜索視圖:

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

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

視圖組件的視圖名稱默認(rèn)為Default,這意味著您的視圖文件通常將命名為Default.cshtml。創(chuàng)建視圖組件結(jié)果或調(diào)用View方法時,可以指定不同的視圖名稱。

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

調(diào)用視圖組件

要使用視圖組件,請?jiān)谝晥D中調(diào)用以下代碼:

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

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

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

通過標(biāo)簽幫助器調(diào)用視圖組件

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

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

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

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

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

@addTagHelper *, MyWebApp

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

本示例中使用的InvokeAsync方法:

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

標(biāo)簽幫助器標(biāo)記:

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

在上面的示例中,PriorityList視圖組件變?yōu)閜riority-list;視圖組件的參數(shù)作為屬性按小寫短橫線命名方式傳遞。

從控制器直接調(diào)用視圖組件

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

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

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

演練:創(chuàng)建一個簡單的視圖組件

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

添加ViewComponent類

創(chuàng)建一個?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();}} }

代碼注意事項(xiàng):

  • 視圖組件類可以包含在項(xiàng)目中的任何文件夾中。

  • 因?yàn)轭惷QPriorityListViewComponent以后綴ViewComponent結(jié)尾,運(yùn)行時在視圖中引用視圖組件時使用字符串“PriorityList”。稍后我會詳細(xì)解釋一下。

  • [ViewComponent]特性可以更改用于引用視圖組件的名稱。例如,我們可以該類命名為XYZ并應(yīng)用該ViewComponent屬性:

    ? ?[ViewComponent(Name = "PriorityList")] ? ?public class XYZ : ViewComponent
  • [ViewComponent]特性告訴視圖組件選擇器在查找與組件關(guān)聯(lián)的視圖時使用名稱PriorityList,并在從視圖引用組件類時使用字符串“PriorityList”。稍后我會詳細(xì)解釋一下。

  • 組件使用依賴注入來使DbContext可用。

  • InvokeAsync?是一個可以從視圖中調(diào)用的公開方法,它可以使用任意數(shù)量的參數(shù)。

  • InvokeAsync方法返回滿足isDone和maxPriority參數(shù)的ToDo集合。

創(chuàng)建視圖組件Razor視圖

  • 創(chuàng)建Views/Shared/Components文件夾,此文件夾必須命名為?Components。

  • 創(chuàng)建?Views/Shared/Components/PriorityList?文件夾。此文件夾名稱必須與視圖組件類的名稱一致,或者類名稱去掉后綴(如果遵循約定在類名稱中使用ViewComponent后綴)。如果您使用該ViewComponent特性,則名稱需要與特性名稱一致。

  • 創(chuàng)建一個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元素中包含視圖組件的調(diào)用

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

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

調(diào)試應(yīng)用程序,下圖顯示了ToDo列表和選擇項(xiàng):

您也可以直接在控制器中調(diào)用視圖組件:

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

指定視圖名稱

復(fù)雜視圖組件可能需要在某些情況下指定非默認(rèn)視圖。以下代碼顯示了如何從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?文件復(fù)制到名為?Views/Shared/Components/PriorityList/PVC.cshtml?視圖文件。添加標(biāo)題以表示正在使用的是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 })

運(yùn)行應(yīng)用程序并驗(yàn)證是PVC視圖。

如果顯示不是PVC視圖,請驗(yàn)證您調(diào)用視圖組件priority參數(shù)是否為4或更高的。

檢測視圖路徑

  • 將priority參數(shù)更改為三個或更小,返回默認(rèn)視圖。

  • 臨時將?Views/Todo/Components/PriorityList/Default.cshtml?重命名為?1Default.cshtml。

  • 調(diào)試應(yīng)用程序,您將收到以下錯誤:

    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?復(fù)制到?Views/Shared/Components/PriorityList/Default.cshtml?。

  • 在?Shared?的Todo視圖組件視圖中添加一些標(biāo)記,以表示視圖來自?Shared?文件夾。

  • 測試?Shared?組件視圖。

避免字符串魔法

如果要編譯時安全,則可以使用類名替換硬編碼視圖組件名稱。創(chuàng)建沒有以“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運(yùn)算符:

@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

相關(guān)文章:?

  • .NET Core 2.0 正式發(fā)布信息匯總

  • .NET Standard 2.0 特性介紹和使用指南

  • .NET Core 2.0 的dll實(shí)時更新、https、依賴包變更問題及解決

  • .NET Core 2.0 特性介紹和使用指南

  • Entity Framework Core 2.0 新特性

  • 體驗(yàn) PHP under .NET Core

  • .NET Core 2.0使用NLog

  • 升級項(xiàng)目到.NET Core 2.0,在Linux上安裝Docker,并成功部署

  • 解決Visual Studio For Mac Restore失敗的問題

  • ASP.NET Core 2.0 特性介紹和使用指南

  • .Net Core下通過Proxy 模式 使用 WCF

  • .NET Core 2.0 開源Office組件 NPOI

  • ASP.NET Core - Razor頁面之Handlers處理方法

  • ASP.NET Core Razor頁面 vs MVC

  • Razor Page–Asp.Net Core 2.0新功能 ?Razor Page介紹

  • ASP.Net Core 2.0中的Razor Page不是WebForm

原文地址:http://www.cnblogs.com/tdfblog/p/view-components-in-asp-net-core.html


.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關(guān)注

總結(jié)

以上是生活随笔為你收集整理的ASP.NET Core Razor 视图组件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。