6-3.ASP.NET Core MVC 入門教學 - Partial View部分視圖

ASP.NET Core MVC 入門教學

這節要來講Partial View,中文是部分視圖

主要用在多個頁面有使用有同樣的區塊版型,或者可能想要更清楚的架構而將某頁的HTML切成多個部分,方便以後維護

都可以使用Partial View功能將部分的HTML給切分出去,最後再組合成一個完整的HTML

這邊我將News2的Index改造一下,變成區塊顯示新聞

@foreach (var item in Model)
{
    <div class="box">
        <div class="topLine">
        </div>
        <div class="divisionZone">@item.DepartmentName</div>
        <div class="ImageZone">
            <img src="/news.jpg" loading="lazy">
            <div class="dateZone">
                <span>@item.StartDateTime.ToString("yyyy-MM-dd")</span>
            </div>
        </div>
        <div class="textZone">
            <div class="titleBox">
                @item.Title
            </div>
            <hr>
            <div class="contentBox">
                @item.Content
            </div>
        </div>
        <div class="detailZone">
            <a href="/news2/edit/@item.NewsId" rel="noopener noreferrer" target="_blank">
                詳細資料
            </a>
        </div>
    </div>
}
<div style="clear:both"></div>

其中@foreach (var item in Model)之中的版型,我可能很多的頁面都會用到,又或者我不想擺在index之中維護

就可以另外創一個視圖View,在Shared資料夾下中創一個NewsBox

然後我們將上面foreach之中的html都貼來新建的這個檢視頁,以下NewsBox.cshtml內容

@model NewsDto

<div class="box">
    <div class="topLine">
    </div>
    <div class="divisionZone">@Model.DepartmentName</div>
    <div class="ImageZone">
        <img src="/news.jpg" loading="lazy">
        <div class="dateZone">
            <span>@Model.StartDateTime.ToString("yyyy-MM-dd")</span>
        </div>
    </div>
    <div class="textZone">
        <div class="titleBox">
            @Model.Title
        </div>
        <hr>
        <div class="contentBox">
            @Model.Content
        </div>
    </div>
    <div class="detailZone">
        <a href="/news2/edit/@Model.NewsId" rel="noopener noreferrer" target="_blank">
            詳細資料
        </a>
    </div>
</div>

並且在上方宣告Model NewsDto,當然下面對應的變數也要改成model

這個意思是,這個部分視圖將預計會有一個NewsDto類型的資料傳過來,然後我就可以使用該資料顯示在畫面上

然後原來的News2的Index改成引入部分視圖,後面則是傳一個NewsDto變數item進去

@model List<NewsDto>

@{
    ViewData["Title"] = "Index2";
}
@foreach (var item in Model)
{
    <text>
        @await Html.PartialAsync("NewsBox", item)
    </text>
}
<div style="clear:both"></div>

部分引入以下幾種寫法,並分為非同步跟同步寫法

非同步

<partial name="NewsBox" model="item" />
@await Html.PartialAsync("NewsBox", item)
@{
    await Html.RenderPartialAsync("NewsBox", item);
}

同步

@Html.Partial("NewsBox", item)
@{
    Html.RenderPartial("NewsBox", item);
}

每種寫法都有不同的用意,但我這邊推薦一開始也最常用的就好,其他的有遇到特殊用途再研究就好了,這邊就不多說了


@await Html.PartialAsync("NewsBox", item)

這時候我們看一下程式有沒有正常運作

這樣就大功告成,以後其他頁面也可以使用Newsbox的這一個部分視圖了

 

範例檔:下載




Copyright © 凱哥寫程式 2022 | Powered by TalllKai ❤