ASP.NET Core 的部分標記協助程式Partial Tag Helper in ASP.NET Core

作者:Scott AddieBy Scott Addie

如需標籤協助程式的概觀,請參閱 ASP.NET Core 中的標籤協助程式For an overview of Tag Helpers, see ASP.NET Core 中的標籤協助程式.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

總覽Overview

部分標記協助程式用於在 Razor 頁面和 MVC 應用程式中呈現部分檢視The Partial Tag Helper is used for rendering a partial view in Razor Pages and MVC apps. 請考慮它:Consider that it:

  • 需要 ASP.NET Core 2.1 或更新版本。Requires ASP.NET Core 2.1 or later.
  • HTML 協助程式語法的替代方法。Is an alternative to HTML Helper syntax.
  • 以非同步方式呈現部分檢視。Renders the partial view asynchronously.

呈現部分檢視的 HTML 協助程式選項包括:The HTML Helper options for rendering a partial view include:

這整份文件的範例皆使用 Product 模型:The Product model is used in samples throughout this document:

namespace TagHelpersBuiltIn.Models
{
    public class Product
    {
        public int Number { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
    }
}

部分標記協助程式屬性的清查如下。An inventory of the Partial Tag Helper attributes follows.

名稱name

name 屬性 (Attribute) 是必要項。The name attribute is required. 它會指出要呈現之部分檢視的名稱或路徑。It indicates the name or the path of the partial view to be rendered. 當提供部分檢視名稱時,就會起始檢視探索程序。When a partial view name is provided, the view discovery process is initiated. 提供明確的路徑時,則會略過該程序。That process is bypassed when an explicit path is provided. 如需了解所有可接受的 name 值,請參閱部分檢視探索For all acceptable name values, see Partial view discovery.

下列標記會使用明確的路徑,指出將從 Shared 資料夾載入 _ProductPartial.cshtmlThe following markup uses an explicit path, indicating that _ProductPartial.cshtml is to be loaded from the Shared folder. 使用 for 屬性,模型就會傳遞到部分檢視以進行繫結。Using the for attribute, a model is passed to the partial view for binding.

<partial name="Shared/_ProductPartial.cshtml" for="Product">

forfor

for 屬性會針對目前的模型指派一個要評估的 ModelExpressionThe for attribute assigns a ModelExpression to be evaluated against the current model. ModelExpression 可推斷 @Model. 語法。A ModelExpression infers the @Model. syntax. 例如,可以使用 for="Product",而不是 for="@Model.Product"For example, for="Product" can be used instead of for="@Model.Product". 使用 @ 符號來定義內嵌運算式會覆寫這個預設的推斷行為。This default inference behavior is overridden by using the @ symbol to define an inline expression.

下列標記將載入 _ProductPartial.cshtmlThe following markup loads _ProductPartial.cshtml:

<partial name="_ProductPartial" for="Product">

部分檢視會繫結至相關聯的頁面模型 Product 屬性:The partial view is bound to the associated page model's Product property:

using Microsoft.AspNetCore.Mvc.RazorPages;
using TagHelpersBuiltIn.Models;

namespace TagHelpersBuiltIn.Pages
{
    public class ProductModel : PageModel
    {
        public Product Product { get; set; }

        public void OnGet()
        {
            Product = new Product
            {
                Number = 1,
                Name = "Test product",
                Description = "This is a test product"
            };
        }
    }
}

modelmodel

model 屬性指派要傳遞至部分檢視的模型執行個體。The model attribute assigns a model instance to pass to the partial view. model 屬性不能與 for 屬性一起使用。The model attribute can't be used with the for attribute.

在下列標記中,新的 Product 物件將具現化,並傳遞給 model 屬性以進行繫結:In the following markup, a new Product object is instantiated and passed to the model attribute for binding:

<partial name="_ProductPartial"
         model='new Product { Number = 1, Name = "Test product", Description = "This is a test" }'>

view-dataview-data

view-data 屬性指派要傳遞至部分檢視的 ViewDataDictionaryThe view-data attribute assigns a ViewDataDictionary to pass to the partial view. 下列標記會讓整個 ViewData 集合可存取部分檢視:The following markup makes the entire ViewData collection accessible to the partial view:

@{
    ViewData["IsNumberReadOnly"] = true;
}

<partial name="_ProductViewDataPartial" for="Product" view-data="ViewData">

在上述程式碼中,IsNumberReadOnly 索引鍵值會設定為 true,並新增至 ViewData 集合。In the preceding code, the IsNumberReadOnly key value is set to true and added to the ViewData collection. 因此,ViewData["IsNumberReadOnly"] 可以在下列部分檢視內進行存取:Consequently, ViewData["IsNumberReadOnly"] is made accessible within the following partial view:

@model TagHelpersBuiltIn.Models.Product

<div class="form-group">
    <label asp-for="Number"></label>
    @if ((bool)ViewData["IsNumberReadOnly"])
    {
        <input asp-for="Number" type="number" class="form-control" readonly />
    }
    else
    {
        <input asp-for="Number" type="number" class="form-control" />
    }
</div>
<div class="form-group">
    <label asp-for="Name"></label>
    <input asp-for="Name" type="text" class="form-control" />
</div>
<div class="form-group">
    <label asp-for="Description"></label>
    <textarea asp-for="Description" rows="4" cols="50" class="form-control"></textarea>
</div>

在此範例中,ViewData["IsNumberReadOnly"] 的值決定 Number 欄位是否會顯示為唯讀。In this example, the value of ViewData["IsNumberReadOnly"] determines whether the Number field is displayed as read only.

從 HTML 協助程式移轉Migrate from an HTML Helper

請考慮下列非同步 HTML 協助程式範例。Consider the following asynchronous HTML Helper example. 逐一查看和顯示產品集合。A collection of products is iterated and displayed. 依據 PartialAsync 方法的第一個參數載入 _ProductPartial.cshtml部分檢視。Per the PartialAsync method's first parameter, the _ProductPartial.cshtml partial view is loaded. Product 模型的執行個體會傳遞到部分檢視以進行繫結。An instance of the Product model is passed to the partial view for binding.

@foreach (var product in Model.Products)
{
    @await Html.PartialAsync("_ProductPartial", product)
}

下列 Partial 標籤協助程式可完成與 PartialAsync HTML 協助程式相同的非同步轉譯行為。The following Partial Tag Helper achieves the same asynchronous rendering behavior as the PartialAsync HTML Helper. model 屬性會獲指派 Product 模型執行個體,以繫結至部分檢視。The model attribute is assigned a Product model instance for binding to the partial view.

@foreach (var product in Model.Products)
{
    <partial name="_ProductPartial" model="product" />
}

其他資源Additional resources