*紅色字體為固定命名,藍色為一般命名規則,黃色為ASP.NET CORE 默認查找文件名
概要:1.簡單ViewComponent的用法
2.ViewComponent控制器返回值
3.注意事項
1.簡單ViewComponent的用法
第一步:創建ASP.NET CORE Web應用程序,並在網站根目錄創建 ViewComponents 文件夾
第二部:在ViewComponents文件夾中新建視圖組件的控制器, 這兒我命名為 OnePartViewComponent 。 然后編輯該類,繼承ViewComponent,實現InvokeAsync()或Invoke()方法
1 using Microsoft.AspNetCore.Mvc; 2
3 namespace AspCoreTest.ViewComponents 4 { 5 public class OnePartViewComponent : ViewComponent 6 { 7 //public async Task<IViewComponentResult> InvokeAsync()
8 public IViewComponentResult Invoke() 9 { 10 ViewData["Msg"] = "別看了,我就是分布視圖"; 11
12 return View(); 13 } 14 } 15 }
第三步:創建視圖
在Views文件夾下新建 Components 文件夾,在該Components文件夾下建 OnePart 文件夾, 接着在該OnePart文件夾下建視圖頁 Default.cshtml。暫且一行代碼
1 <h1>@ViewData["Msg"]</h1>
到此一個簡單的視圖組件也就創建完了
第四部:在其他頁面插入我們創建的這個視圖組件,這兒我選擇VS自動創建的 About 頁面作為演示
1 @{ 2 ViewData["Title"] = "About"; 3 } 4 <h2>@ViewData["Title"].</h2> 5 6 @await Component.InvokeAsync("OnePart") 7 8 <h3>@ViewData["Message"]</h3> 9 10 <p>Use this area to provide additional information.</p>
F5運行,點擊About,轉到About頁面:

2.視圖組件的控制器返回值
對於正式使用,可能會還會用到Model,在ViewComponent控制器中返回一個model。model文件夾並無明確要求,對視圖組件來說,一般放在 ViewModels 文件夾下,在ViewModels 文件夾下新建 OnePart.class
1 namespace AspCoreTest.ViewModels 2 { 3 public class OnePart 4 { 5 /// <summary> 6 /// 姓名 7 /// </summary> 8 public string name { get; set; } 9 10 /// <summary> 11 /// 性別 12 /// </summary> 13 public string sex { get; set; } 14 } 15 }
在控制器中使用該Model處理數據,並返回給視圖
1 using Microsoft.AspNetCore.Mvc; 2 using AspCoreTest.ViewModels; 3 4 namespace AspCoreTest.ViewComponents 5 { 6 public class OnePartViewComponent : ViewComponent 7 { 8 //public async Task<IViewComponentResult> InvokeAsync() 9 public IViewComponentResult Invoke() 10 { 11 ViewData["Msg"] = "別看了,我就是分布視圖"; 12 13 OnePart onePart = new OnePart();//聲明model 14 //數據處理 15 onePart.name = "Runing"; 16 onePart.sex = "男"; 17 18 //返回model 19 return View(onePart); 20 } 21 } 22 }
在視圖中使用model的數據
@using AspCoreTest.ViewModels @model OnePart <h1>@ViewData["Msg"]</h1> <table> <tr> <td>姓名</td> <td>性別</td> </tr> <tr> <td>@Model.name</td> <td>@Model.sex</td> </tr> </table>
OK,視圖組件中使用Model大致流程就是這樣,是不是感覺很簡單

3.注意事項總結
a.固定命名規則:
文件夾:控制器文件夾 ViewComponents,
視圖文件夾有兩種選擇:1.某個控制器(如:Home)專用的視圖組件 {Home}/Components/{ViewComponent}/
2.全局的視圖組件 Shared/Components/{ViewComponent}/
控制器:名 + ViewComponent
視圖:Default.cshtml為默認查找的視圖,若自定義視圖名,在需要在ViewComponent控制器中返回時指定該視圖即可
return View("MyView");
b.視圖組件控制器中 Invoke()、InvokeAsunc()兩個方法必須有且僅能有一個
