问题描述
<ol>
<li><a href="/my/razor/page/url">Some text</a>
</ol>
如果要在“剃刀页面”中执行此操作,则只需执行以下操作:<a asp-page="MyRazorPage">Some text</a>
是否可以在TagHelper内部执行类似的操作?
解决方法
TagHelper提供HtmlTargetElement
来将属性添加到指定的标签。以将asp-cuspage
添加到标签<a>
为例。方法Init
用于接收指令asp-cuspage=""
中的参数。此方法Process
提供输出属性。
创建类CusAnchorTagHelper
:
[HtmlTargetElement("a")]
public class CusAnchorTagHelper : TagHelper
{
private const string CuspageAttributeName = "asp-cuspage";
[HtmlAttributeName(CuspageAttributeName)]
public string Cuspage { get; set; }
public string Value { get; set; }
public override void Init(TagHelperContext context)
{
if (context.AllAttributes[0].Value != null)
{
Value = context.AllAttributes[0].Value.ToString();
}
base.Init(context);
}
public override void Process(TagHelperContext context,TagHelperOutput output)
{
var reg = new Regex("(?<!^)(?=[A-Z])");
string attr="";
foreach(var a in reg.Split(Value))
{
attr += a + "/";
}
output.Attributes.SetAttribute("href",attr);
}
}
然后,将自定义taghelper程序集注入页面。它将在视图中绘制。
,我找到了答案。
将IUrlHelperFactory
注入到构造函数中,并使用以下属性:
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
然后您可以通过以下方式创建IUrlHelper
:
var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext);
var url = urlHelper.Page("/Clients/Edit",new { Id = myClientId });
output.Content.AppendHtmlLine($"<a href='{url}'>Edit</a>");