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

后端 未结 2 1731
小蘑菇
小蘑菇 2020-12-18 06:41

In Core MVC there is anew concept as Tag helpers.

We could previously create custom html helpers to attach some classes based on the validation data annotations such

2条回答
  •  佛祖请我去吃肉
    2020-12-18 06:57

    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);
            }
        }
    }
    

提交回复
热议问题