温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

asp.net core新特性之TagHelper标签怎么用

发布时间:2021-07-19 09:42:47 来源:亿速云 阅读:101 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关asp.net core新特性之TagHelper标签怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

  首先,我们需要安装一个vs2017插件:Razor Language Services。这个插件能在html中智能提示用户自定义的标签助手。

  https://marketplace.visualstudio.com/items?itemName=ms-madsk.RazorLanguageServices

创建一个asp.net core项目

asp.net core新特性之TagHelper标签怎么用asp.net core新特性之TagHelper标签怎么用

使用微软定义的标签助手,在安装了插件后,使用标签助手的标签会进行高亮显示

asp.net core新特性之TagHelper标签怎么用

上图中environment、link、a标签均使用了标签助手实现各自的功能

<a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">taghelpersample</a>

a标签中通过使用asp-controller,asp-action自定义属性来实现路由访问。

这时有人会说,我也可以使用@Html类来实现相同功能,为什么需要使用TagHelper?

@Html.ActionLink("taghelpersample", "Index", "Home",null, new { Class = "navbar-brand" })

确实,使用@Html帮助类我们能实现相同的功能,但是使用标签助手的方式不是更加符合html的标签语法吗,对于强迫症程序员简直就是福音~~。而且对于标签的原有属性的添加例如class,标签助手的使用也更加方便。

<!--标签助手版form-->
<form asp-controller="Home" asp-action="Index" class="form-horizontal" method="post">

</form>
<!--Html帮助类版form-->
@using (Html.BeginForm("Index", "Home", FormMethod.Post,, new { Class = "form-horizontal" }))
{

}

此外,标签助手的另外一个特色就是可以自定义,具体步骤如下:

(1)创建派生自TagHelper类的Class

 //类会默认转换为<text-collection></text-collection>
   public class TextCollectionTagHelper:TagHelper
 {
  public override void Process(TagHelperContext context, TagHelperOutput output)
  {
   base.Process(context, output);
  }
 }

(2)设置属性与基本类

public string Color { get; set; }

  public override void Process(TagHelperContext context, TagHelperOutput output)
  {
   output.TagName = "div";
   output.Attributes.Add("style", "color:" + Color);
   var text = "Hello,World";
   var h2 = new TagBuilder("h2");
   var h3 = new TagBuilder("h3");
   var h4 = new TagBuilder("h4");
   var h5 = new TagBuilder("h5");
   var h6 = new TagBuilder("h6");
   var h7 = new TagBuilder("h7");
   h2.InnerHtml.Append(text);
   h3.InnerHtml.Append(text);
   h4.InnerHtml.Append(text);
   h5.InnerHtml.Append(text);
   h6.InnerHtml.Append(text);
   h7.InnerHtml.Append(text);
   output.Content.AppendHtml(h2);
   output.Content.AppendHtml(h3);
   output.Content.AppendHtml(h4);
   output.Content.AppendHtml(h5);
   output.Content.AppendHtml(h6);
   output.Content.AppendHtml(h7);
  }

(3)在_ViewImports.cshtml导入类命名空间

@addTagHelper *,taghelpersample

(4)在cshtml中使用标签助手

<text-collection color="red"></text-collection>
<text-collection color="blue"></text-collection>
<text-collection color="#666"></text-collection>

(5)调试效果

asp.net core新特性之TagHelper标签怎么用

感谢各位的阅读!关于“asp.net core新特性之TagHelper标签怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI