gpt4 book ai didi

c# - 如何创建包含其他标签助手的自定义标签助手

转载 作者:行者123 更新时间:2023-12-05 00:40:00 25 4
gpt4 key购买 nike

public class FormControlTextBoxHelper:TagHelper
{

public override void Process(TagHelperContext context, TagHelperOutput output)
{
using (var writer = new StringWriter())
{
writer.Write(@"<div class=""form-group"">");

//Here I want to write <label asp-for="InputModel.Title" class="control-label"></label> and other tag helpers

writer.Write(@"</div>");

output.Content.SetHtmlContent(writer.ToString());

}

}
}

我在 1-2 小时内找不到任何有关如何拥有包含其他标签助手的自定义标签助手的信息。 Microsoft docs展示非常简单的示例,其中不包含很多有意义的信息。

最佳答案

我是在阅读了多篇不同的文章后才弄清楚的。

所以首先你需要在标签助手的构造函数中注入(inject) IHtmlGenerator ,它将生成标签助手 html,元素的生成也需要 ViewContext,您只能将其作为 Attribute 的属性。 ViewContext .

这是 ViewContext 的摘要属性:

Summary:

Specifies that a tag helper property should be set with the current Microsoft.AspNetCore.Mvc.Rendering.ViewContext when creating the tag helper. The property must have a public set method.

代码如下所示:

[HtmlTargetElement("form-control-text-box")]
public class FormControlTextBoxHelper:TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }

private readonly IHtmlGenerator _generator;

[ViewContext]
public ViewContext ViewContext { get; set; }

public FormControlTextBoxHelper(IHtmlGenerator generator)
{
_generator = generator;
}

public override void Process(TagHelperContext context, TagHelperOutput output)
{
using (var writer = new StringWriter())
{
writer.Write(@"<div class=""form-group"">");

var label = _generator.GenerateLabel(
ViewContext,
For.ModelExplorer,
For.Name, null,
new { @class = "control-label" });

label.WriteTo(writer, NullHtmlEncoder.Default);

var textArea = _generator.GenerateTextBox(ViewContext,
For.ModelExplorer,
For.Name,
For.Model,
null,
new { @class = "form-control" });

textArea.WriteTo(writer, NullHtmlEncoder.Default);

var validationMsg = _generator.GenerateValidationMessage(
ViewContext,
For.ModelExplorer,
For.Name,
null,
ViewContext.ValidationMessageElement,
new { @class = "text-danger" });

validationMsg.WriteTo(writer, NullHtmlEncoder.Default);

writer.Write(@"</div>");

output.Content.SetHtmlContent(writer.ToString());

}

}
}

所以这个标签助手叫做 <form-control-text-box asp-for="InputModel.Title"></form-control-text-box>将产生等于:

<div class="form-group">
<label asp-for="InputModel.Title" class="control-label"></label>
<input asp-for="InputModel.Title" class="form-control" />
<span asp-validation-for="InputModel.Title" class="text-danger"></span>
</div>

我希望我能帮助别人更快地弄清楚。

关于c# - 如何创建包含其他标签助手的自定义标签助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51904629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com