ASP.NET Core 中的錨點標籤協助程式Anchor Tag Helper in ASP.NET Core

Peter KellnerScott Addie 撰寫By Peter Kellner and Scott Addie

錨點標籤協助程式藉由新增新的屬性,來增強標準 HTML 錨點 (<a ... ></a>) 標籤。The Anchor Tag Helper enhances the standard HTML anchor (<a ... ></a>) tag by adding new attributes. 依照慣例,屬性名稱的開頭會加上 asp-By convention, the attribute names are prefixed with asp-. 所轉譯錨點元素的 href 屬性值取決於 asp- 屬性的值。The rendered anchor element's href attribute value is determined by the values of the asp- attributes.

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

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

這整份文件的範例皆使用 SpeakerControllerSpeakerController is used in samples throughout this document:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

public class SpeakerController : Controller
{
    private List<Speaker> Speakers =
        new List<Speaker>
        {
            new Speaker {SpeakerId = 10},
            new Speaker {SpeakerId = 11},
            new Speaker {SpeakerId = 12}
        };

    [Route("Speaker/{id:int}")]
    public IActionResult Detail(int id) =>
        View(Speakers.FirstOrDefault(a => a.SpeakerId == id));

    [Route("/Speaker/Evaluations", 
           Name = "speakerevals")]
    public IActionResult Evaluations() => View();

    [Route("/Speaker/EvaluationsCurrent",
           Name = "speakerevalscurrent")]
    public IActionResult Evaluations(
        int speakerId,
        bool currentYear) => View();

    public IActionResult Index() => View(Speakers);
}

public class Speaker
{
    public int SpeakerId { get; set; }
}

錨點標籤協助程式屬性Anchor Tag Helper attributes

asp-controllerasp-controller

asp-controller 屬性指派用於產生 URL 的控制器。The asp-controller attribute assigns the controller used for generating the URL. 下列標記列出所有喇叭:The following markup lists all speakers:

<a asp-controller="Speaker"
   asp-action="Index">All Speakers</a>

產生的 HTML:The generated HTML:

<a href="/Speaker">All Speakers</a>

若僅指定 asp-controller 屬性而未指定 asp-action,則預設的 asp-action 值即為與目前所執行之檢視相關的控制器動作。If the asp-controller attribute is specified and asp-action isn't, the default asp-action value is the controller action associated with the currently executing view. 若在上述的標記中省略 asp-action,且在 HomeController's Index 檢視 (/Home) 使用錨點標籤協助程式,則產生的 HTML 即為:If asp-action is omitted from the preceding markup, and the Anchor Tag Helper is used in HomeController's Index view (/Home), the generated HTML is:

<a href="/Home">All Speakers</a>

asp-actionasp-action

asp-action 屬性值代表所產生 href 屬性中包含的控制器動作名稱。The asp-action attribute value represents the controller action name included in the generated href attribute. 下列標記會將產生的 href 屬性值設為喇叭評估頁面:The following markup sets the generated href attribute value to the speaker evaluations page:

<a asp-controller="Speaker"
   asp-action="Evaluations">Speaker Evaluations</a>

產生的 HTML:The generated HTML:

<a href="/Speaker/Evaluations">Speaker Evaluations</a>

若未指定任何 asp-controller 屬性,則會使用呼叫執行目前檢視之檢視的預設控制器。If no asp-controller attribute is specified, the default controller calling the view executing the current view is used.

asp-action 屬性值為 Index,就不會將任何動作附加至 URL,而導致引動預設的 Index 動作。If the asp-action attribute value is Index, then no action is appended to the URL, leading to the invocation of the default Index action. 指定的動作 (或預設的動作) 必須存在於 asp-controller 所參考的控制器中。The action specified (or defaulted), must exist in the controller referenced in asp-controller.

asp-route-{value}asp-route-{value}

asp-route-{value} 屬性可使用萬用字元路由首碼。The asp-route-{value} attribute enables a wildcard route prefix. 任何佔用 {value} 預留位置的值都會解譯為潛在的路由參數。Any value occupying the {value} placeholder is interpreted as a potential route parameter. 如果找不到預設路由,則會將此路由首碼附加至產生的 href 屬性,作為要求參數與值。If a default route isn't found, this route prefix is appended to the generated href attribute as a request parameter and value. 否則會在路由範本中加以取代。Otherwise, it's substituted in the route template.

請考慮下列控制器動作:Consider the following controller action:

public IActionResult AnchorTagHelper(int id)
{
    var speaker = new Speaker
    {
        SpeakerId = id
    };

    return View(speaker);
}

使用 Startup.Configure 中定義的預設路由範本:With a default route template defined in Startup.Configure:

app.UseMvc(routes =>
{
    // need route and attribute on controller: [Area("Blogs")]
    routes.MapRoute(name: "mvcAreaRoute",
                    template: "{area:exists}/{controller=Home}/{action=Index}");

    // default route for non-areas
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

MVC 檢視會使用動作提供的模型,如下所示:The MVC view uses the model, provided by the action, as follows:

@model Speaker
<!DOCTYPE html>
<html>
<body>
    <a asp-controller="Speaker"
       asp-action="Detail" 
       asp-route-id="@Model.SpeakerId">SpeakerId: @Model.SpeakerId</a>
</body>
</html>

預設路由的 {id?} 預留位置相符。The default route's {id?} placeholder was matched. 產生的 HTML:The generated HTML:

<a href="/Speaker/Detail/12">SpeakerId: 12</a>

假設路由首碼不屬於相符路由範本的一部份,如同下列 MVC 檢視:Assume the route prefix isn't part of the matching routing template, as with the following MVC view:

@model Speaker
<!DOCTYPE html>
<html>
<body>
    <a asp-controller="Speaker"
       asp-action="Detail"
       asp-route-speakerid="@Model.SpeakerId">SpeakerId: @Model.SpeakerId</a>
<body>
</html>

因為在相符路由中找不到 speakerid,所以產生了下列 HTML:The following HTML is generated because speakerid wasn't found in the matching route:

<a href="/Speaker/Detail?speakerid=12">SpeakerId: 12</a>

如果未指定 asp-controllerasp-action,則會遵循與 asp-route 屬性中相同的預設處理。If either asp-controller or asp-action aren't specified, then the same default processing is followed as is in the asp-route attribute.

asp-routeasp-route

asp-route 屬性用於建立直接連結至具名路由的 URL。The asp-route attribute is used for creating a URL linking directly to a named route. 使用路由屬性,路由可以如 SpeakerController 中所示命名並用於其 Evaluations 動作:Using routing attributes, a route can be named as shown in the SpeakerController and used in its Evaluations action:

[Route("/Speaker/Evaluations", 
       Name = "speakerevals")]
public IActionResult Evaluations() => View();

在下列標記中,asp-route 屬性參考了具名路由:In the following markup, the asp-route attribute references the named route:

<a asp-route="speakerevals">Speaker Evaluations</a>

錨點標記協助程式會使用 URL /Speaker/Evaluations,直接對該控制器動作產生路由。The Anchor Tag Helper generates a route directly to that controller action using the URL /Speaker/Evaluations. 產生的 HTML:The generated HTML:

<a href="/Speaker/Evaluations">Speaker Evaluations</a>

如果除了 asp-route,還指定了 asp-controllerasp-action,產生的路由可能不如預期。If asp-controller or asp-action is specified in addition to asp-route, the route generated may not be what you expect. 為避免路由衝突,請勿將 asp-routeasp-controllerasp-action 屬性搭配使用。To avoid a route conflict, asp-route shouldn't be used with the asp-controller and asp-action attributes.

asp-all-route-dataasp-all-route-data

asp-all-route-data 屬性支援建立機碼值組的字典。The asp-all-route-data attribute supports the creation of a dictionary of key-value pairs. 機碼為參數名稱,值則為參數值。The key is the parameter name, and the value is the parameter value.

在下列範例中,會初始化字典,並將其傳遞Razor給視圖。In the following example, a dictionary is initialized and passed to a Razor view. 或者,您也可以使用自己的模型來傳遞資料。Alternatively, the data could be passed in with your model.

@{
var parms = new Dictionary<string, string>
            {
                { "speakerId", "11" },
                { "currentYear", "true" }
            };
}

<a asp-route="speakerevalscurrent"
   asp-all-route-data="parms">Speaker Evaluations</a>

上述程式碼會產生下列 HTML:The preceding code generates the following HTML:

<a href="/Speaker/EvaluationsCurrent?speakerId=11&currentYear=true">Speaker Evaluations</a>

asp-all-route-data 字典已經過扁平化,以產生符合多載 Evaluations 動作之需求的查詢字串。The asp-all-route-data dictionary is flattened to produce a querystring meeting the requirements of the overloaded Evaluations action:

[Route("/Speaker/EvaluationsCurrent",
       Name = "speakerevalscurrent")]
public IActionResult Evaluations(
    int speakerId,
    bool currentYear) => View();

若字典中有任何機碼符合路由參數,這些值在路由中會受到適當地取代。If any keys in the dictionary match route parameters, those values are substituted in the route as appropriate. 其他不相符的值則產生作為要求參數。The other non-matching values are generated as request parameters.

asp-fragmentasp-fragment

asp-fragment 屬性定義要附加至 URL 的 URL 片段。The asp-fragment attribute defines a URL fragment to append to the URL. 錨點標籤協助程式會新增雜湊字元 (#)。The Anchor Tag Helper adds the hash character (#). 請考慮下列標記:Consider the following markup:

<a asp-controller="Speaker"
   asp-action="Evaluations"
   asp-fragment="SpeakerEvaluations">Speaker Evaluations</a>

產生的 HTML:The generated HTML:

<a href="/Speaker/Evaluations#SpeakerEvaluations">Speaker Evaluations</a>

雜湊標籤在建置用戶端應用程式時很實用。Hash tags are useful when building client-side apps. 例如,您可以使用這些標籤在 JavaScript 中輕鬆標記和搜尋。They can be used for easy marking and searching in JavaScript, for example.

asp-areaasp-area

asp-area 屬性設定區域名稱,用以設定合適的路由。The asp-area attribute sets the area name used to set the appropriate route. 下列範例描述了 asp-area 屬性如何造成路由重新對應。The following examples depict how the asp-area attribute causes a remapping of routes.

頁面中Razor的使用方式Usage in Razor Pages

RazorASP.NET Core 2.1 或更新版本中支援頁面區域。 Pages areas are supported in ASP.NET Core 2.1 or later.

請考慮下列目錄階層:Consider the following directory hierarchy:

  • {專案名稱}{Project name}
    • wwwrootwwwroot
    • 區域Areas
      • 工作階段Sessions
        • 頁面Pages
          • _ViewStart. cshtml_ViewStart.cshtml
          • Index.cshtmlIndex.cshtml
          • Index.cshtml.csIndex.cshtml.cs
    • 頁面Pages

參考 [會話] 區域索引 Razor頁面的標記為:The markup to reference the Sessions area Index Razor Page is:

<a asp-area="Sessions"
   asp-page="/Index">View Sessions</a>

產生的 HTML:The generated HTML:

<a href="/Sessions">View Sessions</a>

提示

若要支援Razor頁面應用程式中的區域,請在中Startup.ConfigureServices執行下列其中一項:To support areas in a Razor Pages app, do one of the following in Startup.ConfigureServices:

MVC 中的使用方式Usage in MVC

請考慮下列目錄階層:Consider the following directory hierarchy:

  • {專案名稱}{Project name}
    • wwwrootwwwroot
    • 區域Areas
      • 部落格Blogs
        • ControllersControllers
          • HomeController.csHomeController.cs
        • 檢視Views
          • 首頁Home
            • AboutBlog.cshtmlAboutBlog.cshtml
            • Index.cshtmlIndex.cshtml
          • _ViewStart. cshtml_ViewStart.cshtml
    • ControllersControllers

asp-area 設定為 "Blogs" 會在 此錨點標籤之相關控制器和檢視的路由前面加上目錄 Areas/BlogsSetting asp-area to "Blogs" prefixes the directory Areas/Blogs to the routes of the associated controllers and views for this anchor tag. 要參考 AboutBlog 檢視的標記如下:The markup to reference the AboutBlog view is:

<a asp-area="Blogs"
   asp-controller="Home"
   asp-action="AboutBlog">About Blog</a>

產生的 HTML:The generated HTML:

<a href="/Blogs/Home/AboutBlog">About Blog</a>

提示

若要在 MVC 應用程式中支援區域,路由範本必須包含區域參考 (若其存在)。To support areas in an MVC app, the route template must include a reference to the area, if it exists. 該範本將以 Startup.Configureroutes.MapRoute 方法呼叫的第二個參數表示:That template is represented by the second parameter of the routes.MapRoute method call in Startup.Configure:

app.UseMvc(routes =>
{
    // need route and attribute on controller: [Area("Blogs")]
    routes.MapRoute(name: "mvcAreaRoute",
                    template: "{area:exists}/{controller=Home}/{action=Index}");

    // default route for non-areas
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

asp-protocolasp-protocol

asp-protocol 屬性用於在您的 URL 中指定通訊協定 (例如 https)。The asp-protocol attribute is for specifying a protocol (such as https) in your URL. 例如:For example:

<a asp-protocol="https"
   asp-controller="Home"
   asp-action="About">About</a>

產生的 HTML:The generated HTML:

<a href="https://localhost/Home/About">About</a>

此範本中的主機名稱為 localhost。The host name in the example is localhost. 錨點標籤協助程式使用網站的公用網域來產生 URL。The Anchor Tag Helper uses the website's public domain when generating the URL.

asp-hostasp-host

asp-host 屬性用於在您的 URL 中指定主機名稱。The asp-host attribute is for specifying a host name in your URL. 例如:For example:

<a asp-protocol="https"
   asp-host="microsoft.com"
   asp-controller="Home"
   asp-action="About">About</a>

產生的 HTML:The generated HTML:

<a href="https://microsoft.com/Home/About">About</a>

asp-pageasp-page

[ Asp 頁面] 屬性會與Razor頁面搭配使用。The asp-page attribute is used with Razor Pages. 您可用其將錨點標籤的 href 屬性值設定為特定頁面。Use it to set an anchor tag's href attribute value to a specific page. 在頁面名稱的開頭加上正斜線 ("/") 即可建立 URL。Prefixing the page name with a forward slash ("/") creates the URL.

下列範例會指向 [出席Razor者] 頁面:The following sample points to the attendee Razor Page:

<a asp-page="/Attendee">All Attendees</a>

產生的 HTML:The generated HTML:

<a href="/Attendee">All Attendees</a>

asp-page 屬性與 asp-routeasp-controller 以及 asp-action 屬性互斥。The asp-page attribute is mutually exclusive with the asp-route, asp-controller, and asp-action attributes. 但是,asp-page 可以搭配 asp-route-{value} 使用來控制路由,如下列標記所示:However, asp-page can be used with asp-route-{value} to control routing, as the following markup demonstrates:

<a asp-page="/Attendee"
   asp-route-attendeeid="10">View Attendee</a>

產生的 HTML:The generated HTML:

<a href="/Attendee?attendeeid=10">View Attendee</a>

asp-page-handlerasp-page-handler

Asp 頁面處理常式屬性會與Razor頁面搭配使用。The asp-page-handler attribute is used with Razor Pages. 其用途為建立特定頁面處理常式的連結。It's intended for linking to specific page handlers.

請考慮下列頁面處理常式:Consider the following page handler:

public void OnGetProfile(int attendeeId)
{
    ViewData["AttendeeId"] = attendeeId;

    // code omitted for brevity
}

頁面模型的相關標記會連結到 OnGetProfile 頁面處理常式。The page model's associated markup links to the OnGetProfile page handler. 請注意,asp-page-handler 屬性值中會省略頁面處理常式方法名稱的 On<Verb> 前置詞。Note the On<Verb> prefix of the page handler method name is omitted in the asp-page-handler attribute value. 如果這是非同步方法,則 Async 後置詞也會一併省略。When the method is asynchronous, the Async suffix is omitted, too.

<a asp-page="/Attendee"
   asp-page-handler="Profile"
   asp-route-attendeeid="12">Attendee Profile</a>

產生的 HTML:The generated HTML:

<a href="/Attendee?attendeeid=12&handler=Profile">Attendee Profile</a>

其他資源Additional resources