又一个新的名词 (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>
来源: https://www.cnblogs.com/yyfh/p/11541067.html