在自定义标签助手中使用Razor标签助手 [英] Use Razor Tag helpers inside custom tag helper
问题描述
你好,这是我的标签助手
Hello this is my tag helper
[HtmlTargetElement("card")]
public class CardTagHelper : TagHelper
{
public string Title { get; set; }
public string Icon { get; set; }
public string Url { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "CardTagHelper";
output.TagMode = TagMode.StartTagAndEndTag;
var preContent = new StringBuilder();
preContent.AppendFormat($@"
<div class='card custom-card'>
<div class='card-header'>
<div class='card-title'>");
if (Url != null)
{
preContent.AppendFormat($@"
<a asp-for='{Url}'>
<div class='float-left return'>
<i class='fas fa-arrow-alt-circle-left fa-lg'></i>
</div>
</a>");
}
preContent.AppendFormat($@"<i class='{Icon}'></i>
{Title}
</div>
</div>
<div class='card-body'>");
var postContent = new StringBuilder();
postContent.AppendFormat($@"
</div>
<div class='card-footer'>
</div>
</div>");
output.PreContent.SetHtmlContent(preContent.ToString());
output.PostContent.SetHtmlContent(postContent.ToString());
}
}
}
输出为自举4卡
<card title="myTitle" icon="myIcon" url="redirectUrl">
// Content here
</card>
我的问题是我想在条件渲染字符串上使用asp页而不是href锚,但是当我添加它时,它没有任何作用或任何可点击的操作。
my problem is that i would like to use asp-page instead of href on the conditional rendered string for the anchor but when i added it, it had no effect or any clickable.
EDIT
这些是我的viewimport,正如我建议的那样,我尝试在Asp.Net Core之前包括我的自定义帮助程序
These are my viewimports, as suggested i tried include my custom helper before the Asp.Net Core
@using MyProject
@namespace MyProject.Pages
@addTagHelper *, MyProject
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
推荐答案
但是,我没有找到任何文章解释如何在自定义标签帮助器中使用Razor标签帮助器。但是对于我的解决方案,我不得不使用实际的 href标签,而不是如下所示的 asp-for剃刀标签助手。
However, I didn't find any article where it is explained how we can use Razor Tag helpers inside our custom tag helpers. but for my solution, i had to use actual 'href' tag instead of 'asp-for' razor tag helper like below.
public string Url { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var content = $@"<a class='nav-link text-dark' href='/{Url}'>{Title}</a>";
output.TagName = "li";
output.Content.SetHtmlContent(content);
output.Attributes.Add("class", "nav-item");
}
Razor标签助手的行为与您为@Jackal所做的相同。生成的HTML如下-
Razor tag helper did behave the same it is doing for you, @Jackal. HTML generated like below -
<li class="nav-item"><a class="nav-link text-dark" href="/Index">Home</a></li>
<li class="nav-item"><a class="nav-link text-dark" href="/Restaurants/List">Restaurants</a></li>
希望,它会有所帮助。谢谢
Hope, it helps. Thanks
这篇关于在自定义标签助手中使用Razor标签助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!