1. 程式人生 > 實用技巧 >ASP.Net Core -- View Components

ASP.Net Core -- View Components

View Components:和分佈檢視差不多,但是它有獨立的資料來源,如下:

1:可複用

2:獨立的元件

3:有獨立的邏輯/資料

4:相當於迷你MVC請求

5:不依賴於父級view的資料

看一張圖:

外層使用佈局頁,內層為index.cshtml,比如裡邊的Model存放的學生資訊,但是頁面的下方可能需要一些其它內容,比如,今天有哪些課程,而這些資料和index裡的資料根本不在一個邏輯,index裡對應的控制器只負責學生列表資訊,而課程資訊需要從另外一個數據源讀取,這個時候就可以使用View Components。

程式碼示例:

通常View Components放在一個名為“ViewComponents”的資料夾下,裡邊新建一個C#類,命名方式和控制器差不多,後邊以ViewComponent結尾,這個類用來獲取資料來源,就像MVC裡的控制器一樣,它也有對應的Razer view,

public class WelcomeViewComponent : ViewComponent
    {
        private readonly IRepository<Student> _repository;

        public WelcomeViewComponent(IRepository<Student> repository)
        {
            _repository = repository;
        }
        public IViewComponentResult Invoke()
        {
            var count = _repository.GetAll().Count().ToString();
            return View("Default", count);
        }
    }

1:裡邊的動作實現了IViewComponentResult這個介面物件,可不是IActionResult!

2:裡邊的動作返回學生列表總數。它對應的檢視和分佈檢視一樣,放在shared檔案下,那麼所有的檢視都可以使用。

3:在Shared資料夾裡新建一個Components資料夾,裡邊再新建一個Welcome資料夾。

4:在裡邊新建一個名為_Default.cshtml的檔案,然後裡邊正常寫程式碼就行,如下:

@model string

<h1>學生總數:@Model</h1>

接收string型別的資料,然後就可以呼叫了,在佈局頁呼叫,如下:

@await Component.InvokeAsync("Welcome")

這樣,頁面載入後,下方就會顯示學生總數,當然,在asp.net core裡邊使用TagHelper最好,如下:

<vc:welcome></vc:welcome>

這個時候還不可以用,因為這資料我們自己定義的TagHelper,需要引用一下,在_ViewImports裡新增:

@addTagHelper *,Tutorials.Web

後邊的是我專案名稱,這樣就可以使用該標籤了。現在WelcomeViewComponent這個類,前邊只有一個單詞,如果單詞比較多的話,比如:WelcomeStudentViewComponent,那麼,使用TagHelper標籤的話,就應該用短橫線隔開來命名,如下:

<vc:welcome-student></vc:welcome-student>

注意,依舊是小寫字母。