ASP.NET Core 中的部分檢視Partial views in ASP.NET Core

作者:Steve SmithMaher JENDOUBIRick AndersonScott SauberBy Steve Smith, Maher JENDOUBI, Rick Anderson, and Scott Sauber

部分視圖是在 Razor 另一個標記檔案轉譯輸出呈現 HTML 輸出的標記檔案(. cshtml)。A partial view is a Razor markup file (.cshtml) that renders HTML output within another markup file's rendered output.

開發 MVC 應用程式(其中標記檔案稱為views)或頁面應用程式(其中標記檔案稱為頁面)時,會使用「部分視圖」一詞 Razor 。 pagesThe term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages. 本主題的一般是以標記檔案的形式來參考 MVC views 和 Razor pages 頁面。 markup filesThis topic generically refers to MVC views and Razor Pages pages as markup files.

查看或下載範例程式碼如何下載View or download sample code (how to download)

使用部分檢視的時機When to use partial views

針對下列項目,部分檢視是有效的方法:Partial views are an effective way to:

  • 將大型標記檔案分解為較小的元件。Break up large markup files into smaller components.

    在由多個邏輯部分組成的大型複雜標記檔案中,使用隔離至部分檢視中的每個部分具有優勢。In a large, complex markup file composed of several logical pieces, there's an advantage to working with each piece isolated into a partial view. 標記檔案中的程式碼為可管理,因為標記僅包含整體頁面結構和對部分檢視的參考。The code in the markup file is manageable because the markup only contains the overall page structure and references to partial views.

  • 減少標記檔案中一般標記內容的重複。Reduce the duplication of common markup content across markup files.

    當在標記檔案中使用相同的標記項目時,部分檢視會將重複的標記內容移除至某個部分檢視檔案中。When the same markup elements are used across markup files, a partial view removes the duplication of markup content into one partial view file. 在部分檢視中變更標記時,會更新使用部分檢視之標記檔案的轉譯輸出。When the markup is changed in the partial view, it updates the rendered output of the markup files that use the partial view.

部分檢視不應該用於維護一般版面配置項目。Partial views shouldn't be used to maintain common layout elements. 您應該在 _Layout.cshtml 檔案中指定一般版面配置項目。Common layout elements should be specified in _Layout.cshtml files.

請勿使用需要複雜轉譯邏輯或程式碼執行來轉譯標記的部分檢視。Don't use a partial view where complex rendering logic or code execution is required to render the markup. 請使用檢視元件,而非部分檢視。Instead of a partial view, use a view component.

宣告部分檢視Declare partial views

部分視圖是在Views資料夾(MVC)或pages資料夾(pages)中維護的 . cshtml標記檔案。 RazorA partial view is a .cshtml markup file maintained within the Views folder (MVC) or Pages folder (Razor Pages).

在 ASP.NET Core MVC 中,控制器的 ViewResult 能夠傳回檢視或部分檢視。In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. 在 Razor 頁面中, PageModel 可以傳回以物件表示的部分視圖 PartialViewResultIn Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. 參考部分檢視一節介紹參考和轉譯部分檢視。Referencing and rendering partial views is described in the Reference a partial view section.

不同於 MVC 檢視或網頁轉譯,部分檢視不會執行 _ViewStart.cshtmlUnlike MVC view or page rendering, a partial view doesn't run _ViewStart.cshtml. 如需 _ViewStart.cshtml 的詳細資訊,請參閱 ASP.NET Core 中的配置For more information on _ViewStart.cshtml, see ASP.NET Core 中的配置.

部分檢視檔案名稱通常以底線 (_) 開頭。Partial view file names often begin with an underscore (_). 您不一定要依照這項慣例命名,但最好先在視覺呈現上將部分檢視與檢視和頁面區別開來。This naming convention isn't required, but it helps to visually differentiate partial views from views and pages.

部分檢視是在「檢視」** 資料夾中維護的 .cshtml 標記檔案。A partial view is a .cshtml markup file maintained within the Views folder.

控制器的 ViewResult 能夠傳回檢視或部分檢視。A controller's ViewResult is capable of returning either a view or a partial view. 參考部分檢視一節介紹參考和轉譯部分檢視。Referencing and rendering partial views is described in the Reference a partial view section.

不同於 MVC 檢視轉譯,部分檢視不會執行 _ViewStart.cshtmlUnlike MVC view rendering, a partial view doesn't run _ViewStart.cshtml. 如需 _ViewStart.cshtml 的詳細資訊,請參閱 ASP.NET Core 中的配置For more information on _ViewStart.cshtml, see ASP.NET Core 中的配置.

部分檢視檔案名稱通常以底線 (_) 開頭。Partial view file names often begin with an underscore (_). 您不一定要依照這項慣例命名,但最好先在視覺呈現上將部分檢視與檢視區別開來。This naming convention isn't required, but it helps to visually differentiate partial views from views.

參考部分檢視Reference a partial view

在頁面 PageModel 中使用部分視圖 RazorUse a partial view in a Razor Pages PageModel

在 ASP.NET Core 2.0 或2.1 中,下列處理常式方法會將* _ AuthorPartialRP*部分視圖呈現給回應:In ASP.NET Core 2.0 or 2.1, the following handler method renders the _AuthorPartialRP.cshtml partial view to the response:

public IActionResult OnGetPartial() =>
    new PartialViewResult
    {
        ViewName = "_AuthorPartialRP",
        ViewData = ViewData,
    };

在 ASP.NET Core 2.2 或更新版本中,處理常式方法也可以呼叫 Partial 方法來產生 PartialViewResult 物件:In ASP.NET Core 2.2 or later, a handler method can alternatively call the Partial method to produce a PartialViewResult object:

public IActionResult OnGetPartial() =>
    Partial("_AuthorPartialRP");

在標記檔案中使用部分檢視Use a partial view in a markup file

在標記檔案中,您可以使用數種方法參考部分檢視。Within a markup file, there are several ways to reference a partial view. 我們建議應用程式使用下列其中一個非同步轉譯方法:We recommend that apps use one of the following asynchronous rendering approaches:

在標記檔案中,您可以使用兩種方法參考部分檢視:Within a markup file, there are two ways to reference a partial view:

我們建議應用程式使用非同步 HTML 協助程式We recommend that apps use the Asynchronous HTML Helper.

Partial 標籤協助程式Partial Tag Helper

部分標記協助程式需要 ASP.NET Core 2.1 或更新版本。The Partial Tag Helper requires ASP.NET Core 2.1 or later.

部分標籤協助程式會以非同步方式轉譯內容,並使用類似於 HTML 的語法:The Partial Tag Helper renders content asynchronously and uses an HTML-like syntax:

<partial name="_PartialName" />

當存在檔案副檔名時,部分標籤協助程式會參考部分檢視,該檢視必須與呼叫部分檢視的標記檔案位於相同資料夾中:When a file extension is present, the Tag Helper references a partial view that must be in the same folder as the markup file calling the partial view:

<partial name="_PartialName.cshtml" />

下列範例會從應用程式根目錄參考部分檢視。The following example references a partial view from the app root. 開頭為波狀符號斜線 (~/) 或斜線 (/) 的路徑表示應用程式根目錄:Paths that start with a tilde-slash (~/) or a slash (/) refer to the app root:

Razor頁面Razor Pages

<partial name="~/Pages/Folder/_PartialName.cshtml" />
<partial name="/Pages/Folder/_PartialName.cshtml" />

MVCMVC

<partial name="~/Views/Folder/_PartialName.cshtml" />
<partial name="/Views/Folder/_PartialName.cshtml" />

下列範例會以相對路徑參考部分檢視:The following example references a partial view with a relative path:

<partial name="../Account/_PartialName.cshtml" />

如需詳細資訊,請參閱 ASP.NET Core 的部分標記協助程式For more information, see ASP.NET Core 的部分標記協助程式.

非同步 HTML 協助程式Asynchronous HTML Helper

使用 HTML 協助程式時,最佳做法是使用 PartialAsyncWhen using an HTML Helper, the best practice is to use PartialAsync. PartialAsync 會傳回包裝在 Task<TResult>IHtmlContent 類型。PartialAsync returns an IHtmlContent type wrapped in a Task<TResult>. 方法的參考方式,是在等候的呼叫前面加上 @ 字元:The method is referenced by prefixing the awaited call with an @ character:

@await Html.PartialAsync("_PartialName")

當存在檔案副檔名時,HTML 協助程式會參考部分檢視,該檢視必須與呼叫部分檢視的標記檔案位於相同資料夾中:When the file extension is present, the HTML Helper references a partial view that must be in the same folder as the markup file calling the partial view:

@await Html.PartialAsync("_PartialName.cshtml")

下列範例會從應用程式根目錄參考部分檢視。The following example references a partial view from the app root. 開頭為波狀符號斜線 (~/) 或斜線 (/) 的路徑表示應用程式根目錄:Paths that start with a tilde-slash (~/) or a slash (/) refer to the app root:

Razor頁面Razor Pages

@await Html.PartialAsync("~/Pages/Folder/_PartialName.cshtml")
@await Html.PartialAsync("/Pages/Folder/_PartialName.cshtml")

MVCMVC

@await Html.PartialAsync("~/Views/Folder/_PartialName.cshtml")
@await Html.PartialAsync("/Views/Folder/_PartialName.cshtml")

下列範例會以相對路徑參考部分檢視:The following example references a partial view with a relative path:

@await Html.PartialAsync("../Account/_LoginPartial.cshtml")

或者,您可以使用 RenderPartialAsync 轉譯部分檢視。Alternatively, you can render a partial view with RenderPartialAsync. 此方法不會傳回 IHtmlContentThis method doesn't return an IHtmlContent. ,而是將轉譯輸出直接串流給回應。It streams the rendered output directly to the response. 因為方法不會傳回結果,所以必須在程式碼區塊內呼叫它 Razor :Because the method doesn't return a result, it must be called within a Razor code block:

@{
    await Html.RenderPartialAsync("_AuthorPartial");
}

由於 RenderPartialAsync 會串流轉譯的內容,因此在某些情況下可提供更好的效能。Since RenderPartialAsync streams rendered content, it provides better performance in some scenarios. 在效能十分重要的情況下,請使用這兩種方法對頁面進行效能評定,並使用可產生更快速回應的方法。In performance-critical situations, benchmark the page using both approaches and use the approach that generates a faster response.

同步 HTML 協助程式Synchronous HTML Helper

PartialRenderPartial 分別是 PartialAsyncRenderPartialAsync 的同步對等方法。Partial and RenderPartial are the synchronous equivalents of PartialAsync and RenderPartialAsync, respectively. 不建議使用同步對等,原因是會出現這些方法發生死結的情況。The synchronous equivalents aren't recommended because there are scenarios in which they deadlock. 同步方法將於未來版本中移除。The synchronous methods are targeted for removal in a future release.

重要

如果您需要執行程式碼,請使用檢視元件,而非部分檢視。If you need to execute code, use a view component instead of a partial view.

呼叫 PartialRenderPartial 會產生 Visual Studio Analyzer 警告。Calling Partial or RenderPartial results in a Visual Studio analyzer warning. 例如,Partial 的存在會產生下列警告訊息:For example, the presence of Partial yields the following warning message:

使用 IHtmlHelper.Partial 可能會導致應用程式死結。Use of IHtmlHelper.Partial may result in application deadlocks. 請考慮使用<部分>標籤協助程式或 IHtmlHelper.PartialAsync。Consider using <partial> Tag Helper or IHtmlHelper.PartialAsync.

將對的呼叫取代為 @Html.Partial @await Html.PartialAsync部分標記協助程式。Replace calls to @Html.Partial with @await Html.PartialAsync or the Partial Tag Helper. 如需 Partial 標籤協助程式移轉的詳細資訊,請參閱從 HTML 協助程式移轉For more information on Partial Tag Helper migration, see Migrate from an HTML Helper.

部分檢視探索Partial view discovery

如果以不含檔案副檔名的名稱參考部分檢視,則會依所述順序搜尋下列位置:When a partial view is referenced by name without a file extension, the following locations are searched in the stated order:

Razor頁面Razor Pages

  1. 目前正在執行頁面的資料夾Currently executing page's folder
  2. 頁面資料夾上方的目錄圖表Directory graph above the page's folder
  3. /Shared
  4. /Pages/Shared
  5. /Views/Shared

MVCMVC

  1. /Areas/<Area-Name>/Views/<Controller-Name>
  2. /Areas/<Area-Name>/Views/Shared
  3. /Views/Shared
  4. /Pages/Shared
  1. /Areas/<Area-Name>/Views/<Controller-Name>
  2. /Areas/<Area-Name>/Views/Shared
  3. /Views/Shared

部分檢視探索適用於下列慣例:The following conventions apply to partial view discovery:

  • 當部分檢視位於不同的資料夾中時,可允許使用具有相同檔案名稱的不同部分檢視。Different partial views with the same file name are allowed when the partial views are in different folders.
  • 當以不含檔案副檔名的名稱參考部分檢視,且部分檢視出現在呼叫者的資料夾和共用資料夾中時,呼叫者資料夾中的部分檢視會提供部分檢視。When referencing a partial view by name without a file extension and the partial view is present in both the caller's folder and the Shared folder, the partial view in the caller's folder supplies the partial view. 如果呼叫者資料夾中不存在部分檢視,則會從「共用」** 資料夾中提供部分檢視。If the partial view isn't present in the caller's folder, the partial view is provided from the Shared folder. 「共用」** 資料夾中的部分檢視稱為「共用部分檢視」** 或「預設部分檢視」**。Partial views in the Shared folder are called shared partial views or default partial views.
  • 部分視圖可以連結 — ,部分視圖可以在呼叫不是由迴圈參考時呼叫另一個部分視圖。Partial views can be chained—a partial view can call another partial view if a circular reference isn't formed by the calls. 相對路徑一律相對於目前的檔案,而不是相對於檔案的根目錄或父檔案。Relative paths are always relative to the current file, not to the root or parent of the file.

注意

Razor section 父標記檔案不會顯示在部分視圖中定義的。A Razor section defined in a partial view is invisible to parent markup files. section 只會顯示在具有其定義的部分檢視。The section is only visible to the partial view in which it's defined.

從部分檢視存取資料Access data from partial views

將部分檢視具現化時,會收到父檢視 ViewData 字典的複本When a partial view is instantiated, it receives a copy of the parent's ViewData dictionary. 父檢視不會保存部分檢視內的資料更新。Updates made to the data within the partial view aren't persisted to the parent view. 傳回部分檢視時,部分檢視內的 ViewData 變更會遺失。ViewData changes in a partial view are lost when the partial view returns.

下列範例示範如何將 ViewDataDictionary 的執行個體傳遞給部分檢視:The following example demonstrates how to pass an instance of ViewDataDictionary to a partial view:

@await Html.PartialAsync("_PartialName", customViewData)

您可以將模型傳入部分檢視。You can pass a model into a partial view. 模型可以是自訂物件。The model can be a custom object. 您可以使用 PartialAsync (對呼叫者呈現內容區塊) 或 RenderPartialAsync (將內容串流至輸出) 來傳遞模型:You can pass a model with PartialAsync (renders a block of content to the caller) or RenderPartialAsync (streams the content to the output):

@await Html.PartialAsync("_PartialName", model)

Razor頁面Razor Pages

範例應用程式中的下列標記來自 Pages/ArticlesRP/ReadRP.cshtml 頁面。The following markup in the sample app is from the Pages/ArticlesRP/ReadRP.cshtml page. 此頁面包含兩個部分檢視。The page contains two partial views. 第二個部分檢視將模型和 ViewData 傳入部分檢視。The second partial view passes in a model and ViewData to the partial view. ViewDataDictionary 建構函式多載用於傳遞新的 ViewData 字典,同時保留現有的 ViewData 字典。The ViewDataDictionary constructor overload is used to pass a new ViewData dictionary while retaining the existing ViewData dictionary.

@model ReadRPModel

<h2>@Model.Article.Title</h2>
@* Pass the author's name to Pages\Shared\_AuthorPartialRP.cshtml *@
@await Html.PartialAsync("../Shared/_AuthorPartialRP", Model.Article.AuthorName)
@Model.Article.PublicationDate

@* Loop over the Sections and pass in a section and additional ViewData to 
   the strongly typed Pages\ArticlesRP\_ArticleSectionRP.cshtml partial view. *@
@{
    var index = 0;

    foreach (var section in Model.Article.Sections)
    {
        await Html.PartialAsync("_ArticleSectionRP", 
                                section,
                                new ViewDataDictionary(ViewData)
                                {
                                    { "index", index }
                                });

        index++;
    }
}

Pages/Shared/_AuthorPartialRP.cshtml 是由 ReadRP.cshtml 標記檔案參考的第一個部分檢視:Pages/Shared/_AuthorPartialRP.cshtml is the first partial view referenced by the ReadRP.cshtml markup file:

@model string
<div>
    <h3>@Model</h3>
    This partial view from /Pages/Shared/_AuthorPartialRP.cshtml.
</div>

Pages/ArticlesRP/_ArticleSectionRP.cshtml 是由 ReadRP.cshtml 標記檔案參考的第二個部分檢視:Pages/ArticlesRP/_ArticleSectionRP.cshtml is the second partial view referenced by the ReadRP.cshtml markup file:

@using PartialViewsSample.ViewModels
@model ArticleSection

<h3>@Model.Title Index: @ViewData["index"]</h3>
<div>
    @Model.Content
</div>

MVCMVC

範例應用程式中的下列標記顯示 Views/Articles/Read.cshtml 檢視。The following markup in the sample app shows the Views/Articles/Read.cshtml view. 此檢視包含兩個部分檢視。The view contains two partial views. 第二個部分檢視將模型和 ViewData 傳入部分檢視。The second partial view passes in a model and ViewData to the partial view. ViewDataDictionary 建構函式多載用於傳遞新的 ViewData 字典,同時保留現有的 ViewData 字典。The ViewDataDictionary constructor overload is used to pass a new ViewData dictionary while retaining the existing ViewData dictionary.

@model PartialViewsSample.ViewModels.Article

<h2>@Model.Title</h2>
@* Pass the author's name to Views\Shared\_AuthorPartial.cshtml *@
@await Html.PartialAsync("_AuthorPartial", Model.AuthorName)
@Model.PublicationDate

@* Loop over the Sections and pass in a section and additional ViewData to 
   the strongly typed Views\Articles\_ArticleSection.cshtml partial view. *@
@{
    var index = 0;

    foreach (var section in Model.Sections)
    {
        await Html.PartialAsync("_ArticleSection", 
                                section,
                                new ViewDataDictionary(ViewData)
                                {
                                    { "index", index }
                                });

        index++;
    }
}

Views/Shared/_AuthorPartial。 cshtmlRead. cshtml標記檔案所參考的第一個部分視圖:Views/Shared/_AuthorPartial.cshtml is the first partial view referenced by the Read.cshtml markup file:

@model string
<div>
    <h3>@Model</h3>
    This partial view from /Views/Shared/_AuthorPartial.cshtml.
</div>

Views/Articles/_ArticleSection.cshtml 是由 Read.cshtml 標記檔案參考的第二個部分檢視:Views/Articles/_ArticleSection.cshtml is the second partial view referenced by the Read.cshtml markup file:

@using PartialViewsSample.ViewModels
@model ArticleSection

<h3>@Model.Title Index: @ViewData["index"]</h3>
<div>
    @Model.Content
</div>

在執行階段期間,會將部分檢視轉譯為父標記檔案的轉譯輸出,而這個父檢視本身則在共用的 _Layout.cshtml 中轉譯。At runtime, the partials are rendered into the parent markup file's rendered output, which itself is rendered within the shared _Layout.cshtml. 第一個部分檢視會轉譯文章作者的名稱和發行日期:The first partial view renders the article author's name and publication date:

Abraham LincolnAbraham Lincoln

此部分檢視來自<共用的部分檢視檔案路徑>。This partial view from <shared partial view file path>. 1863 年 11 月 19 日上午 12:00:0011/19/1863 12:00:00 AM

第二個部分檢視會轉譯文章的章節:The second partial view renders the article's sections:

第一節索引:0Section One Index: 0

八十七年前...Four score and seven years ago ...

第二節索引:1Section Two Index: 1

如今,我們正在進行一場偉大的內戰,考驗著...Now we are engaged in a great civil war, testing ...

第三節索引:2Section Three Index: 2

然而,從更廣泛的意義上說,我們無法在此奉獻...But, in a larger sense, we can not dedicate ...

其他資源Additional resources