asp.net核心标签帮助程序,用于有条件地将类添加到元素 [英] asp.net core tag helper for conditionally add class to an element

查看:65
本文介绍了asp.net核心标签帮助程序,用于有条件地将类添加到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Asp.Net MVC中,我们可以按以下代码有条件地添加类:

In Asp.Net MVC we can add class conditionally as following code:

<div class="choice @(Model.Active?"active":"")">
</div>

如何通过使用tagHelper并删除其他有条件的部件来实现此目的.

How can do this by using tagHelper and by remove else part in condition.

推荐答案

可以通过遵循tagHelper提供的条件来添加条件CSS类. 像AnchorTagHelper asp-route- *这样的代码用于添加路由值.

Ability to add a conditional css class by following tagHelper provides. this code like AnchorTagHelper asp-route-* for add route values acts.

[HtmlTargetElement("div", Attributes = ClassPrefix + "*")]
public class ConditionClassTagHelper : TagHelper
{
    private const string ClassPrefix = "condition-class-";

    [HtmlAttributeName("class")]
    public string CssClass { get; set; }

    private IDictionary<string, bool> _classValues;

    [HtmlAttributeName("", DictionaryAttributePrefix = ClassPrefix)]
    public IDictionary<string, bool> ClassValues
    {
        get {
            return _classValues ?? (_classValues = 
                new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase));
        }
        set{ _classValues = value; }
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var items = _classValues.Where(e => e.Value).Select(e=>e.Key).ToList();

        if (!string.IsNullOrEmpty(CssClass))
        {
            items.Insert(0, CssClass);
        }

        if (items.Any())
        {
            var classes = string.Join(" ", items.ToArray());
            output.Attributes.Add("class", classes);
        }
    }
}

在_ViewImports.cshtml中添加对taghelper的引用,如下所示

in _ViewImports.cshtml add reference to taghelper as following

@addTagHelper "*, WebApplication3"

在视图中使用tagHelper:

Use tagHelper in View:

<div condition-class-active="Model.Active" condition-class-show="Model.Display">
</div>

Active = true和Display = true的结果是:

result for Active = true and Display = true is:

<div class="active show">
</div>

这篇关于asp.net核心标签帮助程序,用于有条件地将类添加到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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