.net core 中的區域視圖組件是ViewComponent,可以用于建制重復使用公共功能組件
一、新建一個類DemoViewComponent(必須以ViewComponent結尾)且繼承ViewComponent
using Microsoft.AspNetCore.Mvc; using NetCoreApiDemo.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace NetCorePortal.Components { public class DemoViewComponent : ViewComponent { public async Task<IViewComponentResult> InvokeAsync() { List<tbl_page> pageList = new List<tbl_page>(); for (int i = 0; i < 10; i++) { pageList.Add(new tbl_page() { page_no = i.ToString(), page_name = i.ToString() }); } return View(pageList);//此處沒有回傳ViewName 對應的視圖檔案是Default.cshtml //return View("D", pageList);//此處回傳的ViewName 是“D” 對應的視圖檔案是D.cshtml } } }
二、在View/Share目錄下建立Components目錄,并在此目錄下建立Demo目錄及對應Default.cshtml檔案
@model IEnumerable<NetCoreApiDemo.Model.tbl_page> <h1>Demo IViewComponentResult</h1> <table> <tr> <th>page_no</th> <th>page_name</th> </tr> @foreach (var item in Model) { <tr> <td>@item.page_no</td> <td>@item.page_name</td> </tr> } </table>
三、呼叫上面建立的 DemoViewComponent
@{ ViewData["Title"] = "Home Page"; } @await Component.InvokeAsync("Demo")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/110591.html
標籤:.NET Core
上一篇:ABP入門教程13 - 更新選單
