在我看来,该参数已成功通过 tag-helper 变体。但是标签 asp-for 属性将被呈现为 asp-for ModelExpression 的名称值(str)而不是 ModelExpression 的模型值(abc)的 for 属性。
根据label taghelper source codes,你可以发现标签助手会调用Generator.GenerateLabel方法来生成标签标签html内容。
Generator.GenerateLabel有五个参数,第三个参数表达式用于生成标签的for属性。
var tagBuilder = Generator.GenerateLabel(
ViewContext,
For.ModelExplorer,
For.Name,
labelText: null,
htmlAttributes: null);
如果你想显示 for 属性的 str 值,你应该创建一个自定义标签 labeltaghelper。
更多细节,您可以参考以下代码:
[HtmlTargetElement("label", Attributes = "asp-for")]
public class ExtendedAspForTagHelper:LabelTagHelper
{
public ExtendedAspForTagHelper(IHtmlGenerator generator)
: base(generator)
{
}
public override int Order => -10000;
//public override void Process(TagHelperContext context, TagHelperOutput output)
//{
// base.Process(context, output);
// if (!output.Attributes.TryGetAttribute("maxlength", out TagHelperAttribute maxLengthAttribute))
// {
// return;
// }
// var description = $"Only <b>{maxLengthAttribute.Value}</b> characters allowed!";
// output.PostElement.AppendHtml(description);
//}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
var tagBuilder = Generator.GenerateLabel(
ViewContext,
For.ModelExplorer,
For.Model.ToString(),
labelText: null,
htmlAttributes: null);
if (tagBuilder != null)
{
output.MergeAttributes(tagBuilder);
// Do not update the content if another tag helper targeting this element has already done so.
if (!output.IsContentModified)
{
// We check for whitespace to detect scenarios such as:
// <label for="Name">
// </label>
var childContent = await output.GetChildContentAsync();
if (childContent.IsEmptyOrWhiteSpace)
{
// Provide default label text (if any) since there was nothing useful in the Razor source.
if (tagBuilder.HasInnerHtml)
{
output.Content.SetHtmlContent(tagBuilder.InnerHtml);
}
}
else
{
output.Content.SetHtmlContent(childContent);
}
}
}
}
}
在 _ViewImports.cshtml 中引入这个 taghelper
@addTagHelper *,[yournamespace]
结果: