ASP.NET Core 中的定位点标记帮助程序Anchor Tag Helper in ASP.NET Core

作者:Peter KellnerScott AddieBy 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-. asp- 属性的值决定呈现的定位点元素的 href 属性值。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)

本文档中的示例均使用 SpeakerController:SpeakerController 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 的索引视图 (/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>

生成以下 HTML,因为匹配的路由中未找到 speakeridThe 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 Pages 中的使用情况Usage in Razor Pages

ASP.NET Core 2.1 或更高版本中支持 Razor Pages 区域。Razor 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 Pages 应用中的区域,请执行以下 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
        • 控制器Controllers
          • HomeController.csHomeController.cs
        • 视图Views
          • 主文件夹Home
            • AboutBlog.cshtmlAboutBlog.cshtml
            • Index.cshtmlIndex.cshtml
          • _ViewStart.cshtml_ViewStart.cshtml
    • 控制器Controllers

如果将 asp-area 设置为 “Blogs”,则会为此定位点标记的关联控制器和视图的路由添加目录 Areas/Blogs 作为前缀。Setting 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.Configure 中的 routes.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-page 属性适用于 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-controllerasp-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-page-handler 属性适用于 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