自定义 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 (将#修改为@)