TagHelpers基于验证属性为LabelTagHelper添加自定义类[必需] [英] TagHelpers add custom class for LabelTagHelper based on validation attribute [Required]

查看:176
本文介绍了TagHelpers基于验证属性为LabelTagHelper添加自定义类[必需]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Core MVC中有一个新的标签帮助器的概念。

In Core MVC there is anew concept as Tag helpers.

我们可以先创建自定义的html帮助器,根据验证数据注释附加一些类]

We could previously create custom html helpers to attach some classes based on the validation data annotations such as [Required].

由于TagHelpers arq相当新的区域,我无法找到anough资源来实现以下操作:

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

视图模型:

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

查看:

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

css:

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

输出:
< a>

output:

但我不想在标签中manully添加所需的css类。不知怎的,我可以扩展LabelTagHelper读取模型数据注释,如果它有[必需],然后在标签元素中添加所需的类。

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.

p>

推荐答案

Yup,你可以通过继承 LabelTagHelper

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("class", 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);
        }
    }
}

这篇关于TagHelpers基于验证属性为LabelTagHelper添加自定义类[必需]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆