当我们写
时<label asp-for="Email"></label>
它生成以下HTML:
<label for="Email">Email Address</label>
工作正常。问题是,是否可以扩展标记帮助以支持添加自定义文本?例如,如果我写
<label asp-for="Email" asp-postfix=":"></label>
它生成以下HTML:
<label for="Email">Email Address:</label>
请注意,冒号现在已添加到标签文本中。并且冒号可以替换为任何其他文本。
答案 0 :(得分:3)
如果您正计划扩展当前的aspnet标记帮助程序,则无法进行。您需要创建自己的标记助手。 aspnet和你的将运行。
[HtmlTargetElement("label", Attributes = _textAttributeName)]
public class PostfixTagHelper : TagHelper
{
private const string _textAttributeName = "postfix-text";
[HtmlAttributeName(_textAttributeName)]
public string Text { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
output.Content.Append(Text);
}
public override int Order
{
get
{
return 100; // Needs to run after aspnet
}
}
}
使用它:
<label asp-for="Email" postfix-text=":"></label>
答案 1 :(得分:0)
这很好用:
<form method="post" class="container mt-3 backgroundwhite w-100">
<div class="form-group row">
<label class="col-4 text-right pr-1" style="" asp-for="ServiceToBeAdded.Name"></label><span>: </span>
<input class="form-control col-6" asp-for="ServiceToBeAdded.Name" type="text" />
</div>
<div class="form-group row">
<label class="col-4 text-right pr-1" asp-for="ServiceToBeAdded.Price"></label><span>: </span>
<input class="form-control col-6" asp-for="ServiceToBeAdded.Price" type="text" />
</div>
</form>
答案 2 :(得分:0)
,然后参考以下链接。 https://github.com/aspnet/Razor/issues/341。供参考,在此添加相同的示例。
源文件
<my-tag-helper>
Content in source
</my-tag-helper>
标记帮助文件。
public void Process(TagHelperContext context, TagHelperOutput output)
{
var nl = Environment.NewLine;
var br = "<br />" + nl;
output.PreElement.Append("This will appear before source element" + br);
output.PreContent.Append(nl + "This will appear before source content" + br);
output.PostContent.Append(br + "This will appear after source content" + nl);
output.PostElement.Append(br + "This will appear after source element");
}
输出。
This will appear before source element<br />
<my-tag-helper>
This will appear before source content<br />
Content in source<br />
This will appear after source content
</my-tag-helper><br />
This will appear after source element