TagHelper使用汇总

1、标签中常用的方法

获取自定义TagHelper中的内容

output.Content.Append("内容");

以上语句会覆盖内部内容

output.Content.GetContent();

通过以上语句获取不到内部内容,可通过以下语句实现:

output.GetChildContentAsync().Result;

 

TagName,SetAttribute 和 SetContent

<email mail-to="123@qq.com" title="title" alt="alt"></email>

output.TagName="a";

替换原标签<email></email>为<a></a>

output.Attributes.SetAttribute("href", "mailto:123@qq.com");

或 output.Attributes.Add("hrefend", "hrefend-value");

设置标签的属性href="mailto:123@qq.com",都为添加标签属性到末尾

<a title="title" alt="alt" href="mailto:123@qq.com" hrefend="hrefend-value">123@qq.com</a>

output.Attributes.Add("hrefend", "hrefend-value");

output.Content.SetContent("abc");

设置标签里的内容文本

RemoveAll、PreContent.SetHtmlContent 和 PostContent.SetHtmlContent

会将带bold的属性移去,设置内容为

用多个 [HtmlTargetElement] 属性修饰类会导致目标出现逻辑 OR。 例如,使用下面的代码时,系统将匹配出 bold 标记或 bold 属性。

[HtmlTargetElement("bold")] [HtmlTargetElement(Attributes = "bold")]

将多个属性添加到同一语句时,运行时会将其视为逻辑 AND。 例如,在下面的代码中,HTML 元素必须命名为“bold”并具有名为“bold”的属性 (<bold bold />) 才能匹配。

[HtmlTargetElement("bold", Attributes = "bold")]

也可使用 [HtmlTargetElement] 更改目标元素的名称。 例如,如果你希望 BoldTagHelper 以 <MyBold> 标记为目标,则可使用以下属性:

[HtmlTargetElement("MyBold")]

 

2、自定义TagHelper建议一些规则

类放在文件夹TagHelpers中,类名为*TagHelper,比如EmailTagHelper,使用驼峰首字母大写。那么对应的标识为字母-字母,如MyEmailTagHelper对应的html为<my-email>,可以使用属性指定标签名称如:

[HtmlTargetElement("MyEmail"]
public class EmailTagHelper:TagHelper

则匹配的标签为<myemail>和<MyEmail>,大小写忽略不计MYemail也可。

3、关于引用

主要引用的是程序集,而不是所有的命名空间

namespace AuthoringTagHelpers.TagHelpers
{
public class EmailTagHelper:TagHelper

{}

}

若要使 EmailTagHelper 类可用于所有 Razor 视图,请将 addTagHelper 指令添加到 views/_ViewImports cshtml 文件中:

@addTagHelper *, AuthoringTagHelpers

若没有标签提示,请编译一下程序。

4、传递类model,条件表达式true或false到自定义taghelper中

@{

Student student=new Student{Name='jone',Old=22};

bool flag=true;

}

<email my-model="student" condition="flag"></email>

<email condition="flag"></email>

 

 

 

声明:本站内容来源于原创和互联网,尊重作者版权,转载请注明来源网址,欢迎收藏,谢谢!