TagHelpers add custom class for LabelTagHelper based on validation attribute [Required]

三世轮回 提交于 2019-12-01 01:29:14

Yup, you can extend this pretty easily by inheriting from the LabelTagHelper class and adding in your own class to the attribute list first.

[HtmlTargetElement("label", Attributes = "asp-for")]
public class RequiredLabelTagHelper : LabelTagHelper
{
    public RequiredLabelTagHelper(IHtmlGenerator generator) : base(generator)
    {
    }

    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        if (For.Metadata.IsRequired)
        {
            CreateOrMergeAttribute("class", "required", output);
        }

        return base.ProcessAsync(context, output);
    }

    private void CreateOrMergeAttribute(string name, object content, TagHelperOutput output)
    {
        var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == name);
        if (currentAttribute == null)
        {
            var attribute = new TagHelperAttribute(name, content);
            output.Attributes.Add(attribute);
        }
        else
        {
            var newAttribute = new TagHelperAttribute(
                name,
                $"{currentAttribute.Value.ToString()} {content.ToString()}",
                currentAttribute.ValueStyle);
            output.Attributes.Remove(currentAttribute);
            output.Attributes.Add(newAttribute);
        }
    }
}
Scott

For answer by Will Ray, I'd like to make a change to the override ProcessAsync as:

public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)

{     

     var isRequired = For.Metadata.ValidatorMetadata.Any(x => 
                         x.GetType().Name.Equals("RequiredAttribute"));
     if (isRequired)
     {
          CreateOrMergeAttribute("class", "required", output);
     }

     return base.ProcessAsync(context, output);
}

Since For.Metadata.IsRequired is always true for boolean properties.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!