首页 > 解决方案 > 如何在自定义 TagHelper 中生成 Razor 页面 url

问题描述

我有一个自定义标签助手,它应该呈现如下内容:

<ol>
  <li><a href="/my/razor/page/url">Some text</a>
</ol>

如果我要在 Razor 页面中执行此操作,我只需执行以下操作:<a asp-page="MyRazorPage">Some text</a>

有没有办法在 TagHelper 内部做类似的事情?

标签: asp.net-coretag-helpersasp.net-core-tag-helpers

解决方案


I found the answer.

Inject IUrlHelperFactory into the constructor as well as use the following property:

[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }

Then you can create an IUrlHelper this way:

var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext);
var url = urlHelper.Page("/Clients/Edit", new { Id = myClientId });
output.Content.AppendHtmlLine($"<a href='{url}'>Edit</a>");

推荐阅读