如何解决如何在自定义TagHelper中生成Razor页面URL
<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>");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。