微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

自定义 TagHelper 呈现单选按钮不会生成所需的验证属性

如何解决自定义 TagHelper 呈现单选按钮不会生成所需的验证属性

我编写了一个生成单选按钮列表的自定义标签助手。在与模型属性关联的属性上,我有一个 required 属性

public enum CustomerType
{
    Private = 1,Business
}

public class NewCustomerSignup
{
    [required]
    public CustomerType CustomerType { get; set; }

    ...
} 

我创建了一个标签助手,为枚举的每个值呈现一个单选按钮:

[HtmlTargetElement("radio-button-list",TagStructure = TagStructure.normalOrSelfClosing)]
public class RadioButtonListTagHelper : TagHelper
{
    private readonly IHtmlGenerator _generator;

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

    [HtmlAttributeName("asp-for")]
    public ModelExpression For { get; set; }

    [HtmlAttributeName("asp-items")]
    public IEnumerable<SelectListItem> Items { get; set; }

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

    public override void Process(TagHelperContext context,TagHelperOutput output)
    {
        using var writer = new StringWriter();

        foreach (var item in this.Items)
        {
            var radioButton = this._generator.GenerateradioButton(this.ViewContext,For.ModelExplorer,For.Name,item.Value,item.Selected,new { id = $"{For.Name}_{item.Value}" });
            
            radioButton.Writeto(writer,NullHtmlEncoder.Default);

            var label = _generator.GenerateLabel(this.ViewContext,item.Text,new { @for = For.Name });

            label.Writeto(writer,NullHtmlEncoder.Default);
        }

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

但它生成了愚蠢的 HTML:

<input data-val="true" data-val-required="The CustomerType field is required." id="CustomerType_1" name="CustomerType" type="radio" value="1" /><label for="CustomerType">Privato</label>
<input id="CustomerType_2" name="CustomerType" type="radio" value="2" /><label for="CustomerType">Azienda</label>

如您所见,只有第一个单选按钮具有验证属性。为什么? 我能做些什么来解决它?

谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。