Partial View:顧名思義,就是一部分視圖,叫“分布視圖”;
1:主要用來復用代碼,它里邊的代碼可以到處復用,就像公有方法一樣。如圖:
2:index.cshtml頁面繼承了布局頁,在index頁面里又使用@HTML.Partial()語句來調用一個分布視圖。
3:第一個參數是分布視圖名稱,第二個參數是從index頁面傳過去的參數內容。
4:分布視圖沒有自己的數據,它里邊的數據需要從調用的一方傳進來。
5:分布視圖的名稱一般是以下划線“_”開頭,比如:_StudentList.cshtml
代碼示例如下:
分布視圖一般建立在shared文件夾下,這樣所有視圖都可以調用,這里我放在Home文件夾下,所以Home文件夾里所有的視圖都可以使用,如下:
我先建立一個名為_StudentTable.cshtml的分布視圖,用來顯示學生信息列表,如下:
@model IEnumerable<StudentViewModel>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年齡</th>
</tr>
</thead>
@foreach (var studentList in Model)
{
<tr>
<td> @studentList.Name</td>
<td>@studentList.Age</td>
</tr>
}
</table>
然后在index.cshtml調用:
@model HomeIndexViewModel <h1>用戶信息列表</h1>
<partial name="_StudentTable" for="studentList"/> @section bottom { <div> <a asp-action="Create">創建一個學生信息</a> </div> }
這樣,在index頁面加載的時候,紅色部分就會顯示學生列表信息。里邊的HTML就是_StudentTable里的代碼。在這里使用的taghelper標簽,所以屬性for里邊直接放HomeIndexViewModel里的屬性就行。
可以再新建一個名為_StudentRow.cshtml的分布視圖,將_StudentTable.cshtml里的tr提取,嵌套着來使用,如下:
@model StudentViewModel
<tr>
<td> @Model.Name</td>
<td>@Model.Age</td>
</tr>
然后在_StudentTable.cshtml里調用:
@model IEnumerable<StudentViewModel>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年齡</th>
</tr>
</thead>
@foreach (var studentList in Model)
{
<partial name="_StudentRow" for="@studentList"/>
}
</table>
這樣,這兩個存放學生列表信息的分布視圖在home文件夾里所有視圖都可以這樣調用。
缺點就是它沒有自己的model