又一个新的名词(taghelper),通过taghelper是可以操作html标签、条件输出、更是自由添加内外元素。当然也内置了挺多的asp-开头的taghelper。

下面文章中也简单的带大家实现一个taghelper;

创建自定义html元素

创建一个类buttontaghelper

tagname为标签名称,下面创建一个button标签

using microsoft.aspnetcore.razor.taghelpers;
namespace ctrl.core.tag.controls.button
{
  [htmltargetelement("test-button")]
  public class buttontaghelper:taghelper
  {
    public override void process(taghelpercontext context, taghelperoutput output)
    {
      output.tagname = "button";
      base.process(context, output);
    }
  }
}

注册taghelper

创建完后可没法执行使用哦,在.cshtml通过某个标签比如form标签输入asp-,下面立刻就出现了一个列表 asp-…. ,这些是怎么做到的呢?因为在_viewimports在我们创建项目工程时,已经提前引入了taghelper默认引入的是微软已经为我们写好的taghelper类库microsoft.aspnetcore.mvc.taghelpers;

我们自定义的话也需要按照这个方式引入自定义的taghelper,下面我自己创建了一个类库名字为”ctrl.core.tag”,我这个类库下面要存放所有的taghelper 我直接引入命名空间

@addtaghelper *,ctrl.core.tag

如果想引入特定的taghelper如下

@addtaghelper 你的taghelper , 命名空间

然后我们测试一下是否可用了,先生成一下项目,然后找个cshtml视图,输入刚才的前缀test会出来刚才定义的标签

添加上并运行项目查看刚才创建的button标签是否存在

添加自定义属性

上面需求是满足不了我们日常需求的,下面我们再定义一个元素属性

 output.attributes.setattribute("class", "btn btn-primary");

然后再打开页面看效果就会看到class元素已经给加上了.

using microsoft.aspnetcore.razor.taghelpers;
namespace ctrl.core.tag.controls.button
{
  [htmltargetelement("test-button")]
  public class buttontaghelper:taghelper
  {
    public override void process(taghelpercontext context, taghelperoutput output)
    {
      output.tagname = "button";
      output.attributes.setattribute("class", "btn btn-primary");
      base.process(context, output);
    }
  }
}

通过vs感知匹配按钮类型

上面能满足我们自定义标签了,但是可能使用起来有局限性,下面我给大家提供一个场景思路,后面大家可以自己进行扩展.

我创建一个枚举类为 ctrlbuttontype

namespace ctrl.core.tag.controls.button
{
  /// <summary>
  ///   按钮类型
  /// </summary>
  public enum ctrlbuttontype
  {
    /// <summary>
    /// 默认样式
    /// </summary>
    default,
    /// <summary>
    ///   首选项
    /// </summary>
    primary,
    /// <summary>
    ///   成功
    /// </summary>
    success,
    /// <summary>
    /// 一般信息
    /// </summary>
    info,
    /// <summary>
    /// 警告
    /// </summary>
    warning,
    /// <summary>
    /// 危险
    /// </summary>
    danger
  }
}

在buttontaghelper类中增加一个属性

public ctrlbuttontype buttontype { get; set; }

到cshtml中添加刚才那个页面的属性,会发现有提示,以及可以看到刚才枚举中定义的.这样通过vs感知以及通过类型指定我们刚才按钮的类型是不是很方面了.

namespace ctrl.core.tag.controls.button
{
  [htmltargetelement("test-button")]
  public class buttontaghelper:taghelper
  {
    public ctrlbuttontype buttontype { get; set; }
    public override void process(taghelpercontext context, taghelperoutput output)
    {
      output.tagname = "button";
      output.attributes.setattribute("class", "btn btn-"+buttontype.tostring().tolower());
      base.process(context, output);
    }
  }
}
<test-button button-type="success"></test-button>

总结

以上所述是www.887551.com给大家介绍的asp.net core razor自定义taghelper,希望对大家有所帮助