ASP Net Core TagHelper添加CSS类

Mit*_*tch 3 css asp.net-core

我需要为必填字段自动显示一个星号,因此我设法在网上找到了一些可以做到这一点的代码。我添加了一个名为“ required-label”的CSS类,也将其变为红色。但是,它仅将CSS类应用于星号,而不将其应用于标签。有什么想法如何将CSS类应用于两者吗?这是要求的完整代码段。

using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;

namespace App.TagHelpers
{
    [HtmlTargetElement("label", Attributes = ForAttributeName)]
    public class LabelRequiredTagHelper : LabelTagHelper
    {
        private const string ForAttributeName = "asp-for";

        public LabelRequiredTagHelper(IHtmlGenerator generator) : base(generator)
        {
        }

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            await base.ProcessAsync(context, output);

            if (For.Metadata.IsRequired)
            {
                var sup = new TagBuilder("sup");
                sup.InnerHtml.Append("*");
                sup.AddCssClass("required-label");
                output.Content.AppendHtml(sup);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢Manoj Kulkarni提供的代码示例。

Dav*_*ang 5

OP中的标签帮助程序可以工作,但我认为无需添加一个sup元素来包含星号,而是要做的就是向标签元素本身添加一个css类,并使用CSS相应地设置标签样式。

稍微调整一下 tag-helper

[HtmlTargetElement("label", Attributes = ForAttributeName)]
public class LabelRequiredTagHelper : LabelTagHelper
{
    private const string ForAttributeName = "asp-for";
    private const string RequiredCssClass = "required";

    public LabelRequiredTagHelper(IHtmlGenerator generator) : base(generator)
    {
    }

    public override async Task ProcessAsync(TagHelperContext context, 
        TagHelperOutput output)
    {
        await base.ProcessAsync(context, output);

        if (For.Metadata.IsRequired)
        {
            output.Attributes.AddCssClass(RequiredCssClass);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

AddCssClass 延期

public static class TagHelperAttributeListExtensions
{
    public static void AddCssClass(this TagHelperAttributeList attributeList, 
        string cssClass)
    {
        var existingCssClassValue = attributeList
            .FirstOrDefault(x => x.Name == "class")?.Value.ToString();

        // If the class attribute doesn't exist, or the class attribute
        // value is empty, just add the CSS class
        if (String.IsNullOrEmpty(existingCssClassValue))
        {
            attributeList.SetAttribute("class", cssClass);
        }
        // Here I use Regular Expression to check if the existing css class
        // value has the css class already. If yes, you don't need to add
        // that css class again. Otherwise you just add the css class along
        // with the existing value.
        // \b indicates a word boundary, as you only want to check if
        // the css class exists as a whole word.  
        else if (!Regex.IsMatch(existingCssClassValue, $@"\b{ cssClass }\b",
            RegexOptions.IgnoreCase))
        {
            attributeList.SetAttribute("class", $"{ cssClass } { existingCssClassValue }");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

视图模型

包含必需属性的示例视图模型,用注释[Required]。默认情况下,还需要一个布尔值。

public class LoginViewModel
{
    [Required]
    public string Username { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember my login?")]
    public bool RememberMe { get; set; }

    public string ReturnUrl { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

风景

例如,我的登录页面为LoginViewModel

@model LoginViewModel
@{
    ViewData["Title"] = "Login";
}

<form asp-area="" asp-controller="account" asp-action="login">
    <input type="hidden" asp-for="ReturnUrl" />

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <div class="form-group">
        <label asp-for="Email"></label>
        <input type="email" class="form-control" asp-for="Email" />
    </div>
    <div class="form-group">
        <label asp-for="Password"></label>
        <input type="password" class="form-control" asp-for="Password" />
    </div>
    <div class="form-group">
        <div class="custom-control custom-checkbox">
            <input type="checkbox" class="custom-control-input" asp-for="RememberMe" />
            <label asp-for="RememberMe" class="custom-control-label"></label>
        </div>
    </div>
    <button type="submit" class="btn btn-primary btn-block">Login</button>
</form>
Run Code Online (Sandbox Code Playgroud)

值得知道的是复选框的标签RememberMe。在视图上,我添加了其他css类custom-control-label,并且标记帮助程序仍设法将所需的css类required与之一起添加。

生成的HTML

在此处输入图片说明

样式(在SASS中)

您可以说我正在使用Bootstrap css框架,并且复选框标签已经有样式,因此我想排除那些样式(由custom-control-labelcss类表示)。

label.required:not(.custom-control-label)::after {
    content: "*";
    padding-left: .3rem;
    color: theme-color('danger');      /* color: #dc3545; */
}
Run Code Online (Sandbox Code Playgroud)

结果

在此处输入图片说明

如果您也希望所需标签也为红色,则可以通过以下方式对其进行样式设置:

label.required:not(.custom-control-label) {
    color: theme-color('danger');      /* color: #dc3545; */

    &::after {
        content: "*";
        padding-left: .3rem;
    }
}
Run Code Online (Sandbox Code Playgroud)