Asp.Net core 視圖組件ViewComponent


視圖組件 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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM