視圖組件 ViewComponent
- 最近用了一下視圖組件,還挺方便的,如果遇到公共的部分,可以抽出來,寫成視圖組件,方便調用
先上圖看一下效果:比如首頁的4個畫紅框的地方是4個模塊,有些地方可能要重復用到,那么我們用視圖組件就很方便。
-
開始編碼步驟
-
第一步,先新建一個項目
原項目中不是包含Components文件夾的,這個是我自己后加上的,創建好Web項目后,添加文件夾Components
-
第二步,添加視圖組件類

創建類過程中,必須要以Name+ViewComponent.cs 為規范,name是自己可以誰意寫的名稱,此類還必須繼承
ViewComponent類,才能實現。接下來在看代碼
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace demoViewComponents.Components { public class OneViewComponent : ViewComponent { /* 如果需要構造函數的話,你就創建 */ /// <summary> /// 構造函數 /// </summary> public OneViewComponent() { } /// <summary> /// 異步調用 /// </summary> /// <returns></returns> public async Task<IViewComponentResult> InvokeAsync() { return View(); } } }
這里說明一下,之前是可以加` public IViewComponentResult Invoke()
{
return View();
} 這個方法,但是現在好像加不了,只能用異步方法,加了會報錯,請測試
-
第三步,添加視圖頁面

必須在Shard文件夾下創建名稱為Components的文件夾,再在此文件夾下創建視圖組件類的前綴名稱Name,如Four文件夾,一般會在此Four文件夾下創建默認的Default.cshtml 頁面,如上圖所示。也可自己指定名稱,不過要在
InvokeAsync方法中返回return View("three");視圖的名稱,例如Three的視圖組件,代碼如下:
namespace demoViewComponents.Components
{
public class ThreeViewComponent : ViewComponent { public async Task<IViewComponentResult> InvokeAsync() { return View("three"); } } }
- 第四步,頁面加載視圖組件
<div class="row"> @await Component.InvokeAsync("One") @await Component.InvokeAsync("Tow") @await Component.InvokeAsync("Three") @await Component.InvokeAsync("Four") </div>
