Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

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

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 as [Required].

As TagHelpers arq quite new area I cannot find anough resources to achieve the following:

here is the view model:

    [Required]
    public Gender Gender { get; set; }

view:

<label class="control-label col-md-3 required" asp-for="Gender"></label>

css:

.required:after {
content: "*";
font-weight: bold;
color: red;
}

output: enter image description here

But I don't want to manully add the required css class in the label. Somehow I shoudl be able to extend the LabelTagHelper to read model data annotations and if it has the [Required] then add required class in the label element.

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...